Python Lesson 05 – Loops

In this tutorial you’ll learn the concept of loop and how to apply it in Python. Particularly, we’ll be talking about for and while loops.

 

What is a Loop?

loop is a code structure that allows a certain block of code to be performed for a defined number of times (for loop) or until a condition is verified (while loop). Essentially, a loop consists in repeating a specific set of instructions.

 

For Loop

In computer science, a for loop specifies iteration. Basically, iteration is the repetition of a process (a set of instructions) to produce a set of outcomes. To better understand this concept, let’s give an example. Imagine you want to print your name 10 times.


my_name = "John" # your name

for i in range(0, 10): # from 0 to 10 (last excluded)
    print(my_name)

In the code above, at line 3 we use the for keyword. It denotes a for loop. Then, we define our index, i for convention (note that you can name the index whatever you want). The index i is actually a variable in the for loopRange(0, 10)  function generates a sequence of numbers, from 0 to 9. In this function the first parameter (0 in our case) represents the initial value of the sequence. Instead, the second parameter (10 in our case) represents the final value of the sequence (not included). Therefore, the sequence will stop at the value 9, for a total of 10 iterations.

The variable i, in each iteration, is assigned the next value. In the first iteration, i is equal to 0 and my_name variable is printed. In the second iteration i is reassigned (it’s now 1) and my_name variable is printed again (as in the first iteration). In the third iteration, i becomes 2, my_name variable is printed. This process continues until the loop had iterated 10 times (the last assignment to i is equal to 9).

To better understand the role of i in the example above, let’s give another example:


for x in range(0, 5): # now we name our index x
    print(x) # Output 0, 1, 2, 3, 4

As you can see running the code above, the numbers from 0 to 4 (both included) are printed. In each iteration, x is incremented by 1 and printed.

Note: in our examples, we can omit the parameter start for the range function (0 in both cases). This parameter is set to 0 by default. Consider the last example.


for x in range(5): # omit start parameter
    print(x) # same output

The range function accepts another parameter which is step. Paired with a for loop, it’s an integer number specifying how much to increase the for loop variable (what we’ve called index up to now). Imagine you want to print only the even numbers from 2 to 10 (both included). The step parameter comes to our aid.


for k in range(2, 11, 2):
    print(k) # Output 2, 4, 6, 8, 10

In the code above, in the range function the first 2 represents the start. Our sequence will start from 2. Note that, in this case, if we omitted the start parameter the sequence would start from 0 by default. Then, 11 represents the end of the sequence (the sequence will stop at 10). Finally, the last 2 is the step parameter. In each iteration, k is incremented by 2 in order to print only the even numbers.

 

While Loop

The while loop consists of a condition (more precisely, a Boolean condition) and a set of instructions to be performed. The condition is evaluated, and if it returns True (Boolean value), the code defined within the loop is executed. The set of instructions is performed until the condition becomes False (so it doesn’t occur). Here’s an example:


x = 0

while x < 10: # until x is less than 10
    print(x) 
    x += 1 # increment x by 1

In the example above, we define our x variable and set it to 0. Then, we instantiate our while loop and specify our condition: x must be less than 10. Until this condition is True, we want to print x variable and increment it by 1. Clearly, at the beginning of the process, x (which is 0) is less than 10. Therefore, the code within the while loop can be performed: x is printed  (value 0 is printed) and x is incremented by 1 and reassigned to the new value 1 through the += (assignment operator).

At the end of 10th iteration, x becomes 10. The condition specified at line 3 returns False (10 isn’t less than 10, obviosuly). Therefore, the while loop stops.

Note: in the example above, if we didn’t apply the increment of 1 of the variable x (line 5), the while loop would continue forever. In this way, x would be equal to 0 forever and the condition of being less than 10 would be True forever.

Imagine now that you want to ask the user for a password. Until the user enters a wrong password, the program asks the user to enter a new password. Once the user enters the correct password, the while loop stops.


x = "" # x is now an empty string

while x != "password": # password is the secret password
    print("Wrong password. Try again.")
    x = input("Enter the password") # ask the user to enter the password

print("Correct!") # code to be executed when the loop stops

Within the while loop, until the user enters a wrong password, we ask for a new password. Then, we assign the new password to the x variable at line 1 and evaluate it: is x equal to the string “password”? If it isn’t, the process is repeated. Otherwise, the we exit the while loop and perform the code defined at line 7. Note that the print at line 7 is not within the while loop because, in terms of indentation, is perfectly aligned with the while keyword.