Loops

Let’s learn about different kinds of loops and the range( ) function.

Loops allow us to repeatedly execute sets of statements for as long as a given condition remains True. There are two kinds of loops in Python— for and while.

The while loop

Before executing the statement (or statements) that is nested in the body of the loop, Python keeps evaluating the test expression (loop test) until the test returns a False value. Let’s start with a simple while loop in the cell below:

Press + to interact
# A simple while loop
i = 1 # initializing a variable i = 1
while i < 5: # loop test
# Run the block of code (given below), till "i < 5"
print('The value of i is: {}'.format(i)) # from your previous lecture, recall the placeholder in the print statement with the format() method!
i = i+1 # increase i by one for each iteration

In the code above, what if we don’t have the i = i+1 statement? Well, as per the rules of the while loop, we’ll get into an infinite while loop. But that is not what we want…

A nicer and cleaner way of exiting the while loop is by using the else statement (optional).

Press + to interact
i=1
while i < 5:
print('The value of i is: {}'.format(i))
i = i+1
else:
print('Exit loop')

The for loop

The for loop is a loop that we use very frequently. The for statement works on strings, lists, tuples, and other built-in iterables, as well as on new user-defined objects.

Let’s create a list my_list of numbers and run a for loop using that list. In a very simple situation, we can execute a block of code using a for loop for every ...