# Loops in Python

Last updated on September 21, 2020

A loop allows us to execute some set of statement multiple times.

Consider the following trivial problem:

Let's say we want to print string "Today is Sunday" 100 times to the console. One way to achieve this is to create a Python script and call print() function 100 times as follows:

 1 2 3 4 5 print("Today is Sunday") # 1st time print("Today is Sunday") # 2nd time ... ... print("Today is Sunday") # 100th time 

As you have probably guessed, this is terribly inefficient way to solve the problem. This program also doesn't scale very well. If we decide to print "Today is Sunday" 1000 times then we would have to write the same statement 900 times more.

We could instead use while loop to re-write the above program as follows:

 1 2 3 4 i = 1 while i <= 100: print("Today is Sunday") i += 1 

At a later date, if we decide to print "Today is Sunday" 1000 times, all we need to do is replace 100 by 1000 and we are done.

Don't worry to much about the syntax of the while loop, in the following section we are discussing everything in great depth.

Python provides two types loops:

1. while loop
2. for loop

## The while loop #

A while loop is a conditionally controlled loop which executes the statements as long as the condition is true. The syntax of the while loop is:

 1 2 3 4 5 6 7 8 while condition: ... 

The first line is known as while clause. Just like if statement, condition is a boolean expression which evaluates to boolean True or False. The indented group of statements is known as the while block or loop body. As usual indentation is required, it tells the Python where block begins and ends.

Here is how it works:

First the condition is evaluated. If the condition is true then statements in the while block is executed. After executing statements in the while block the condition is checked again and if it is still true, then the statements inside the while block is executed again. The statements inside the while block will keep executing until the condition is true. Each execution of the loop body is known as iteration. When the condition becomes false loop terminates and program control comes out of the while loop to begin the execution of statement following it.

Now we know how while loop works. Let's take a good look at the program we used to print "Today is Sunday" to the console.

python101/Chapter-10/a_while_loop.py

 1 2 3 4 i = 1 while i <= 100: print("Today is Sunday") i += 1 

In line 1, we have assigned value 1 to the variable i. When control comes to while loop, the while condition i <= 100 is tested. If it is true, statements inside the while block is executed. The first statement inside the while block prints "Today is Sunday" to the console. The second statement increments the value of the variable i. After executing statements in the while block the condition is tested again. If it is still found to be true, statements inside the while block is executed again. This process keep repeating until i is smaller than or equal to 100. When i becomes 101 while loop terminates and program control comes out of the while loop to execute statement following it.

Example 2: The following program uses while loop to calculate the sum of numbers from 0 to 10

python101/Chapter-10/sum_from_0_to_10.py

 1 2 3 4 5 6 7 i = 1 sum = 0 while i < 11: sum += i # same as sum = sum + i i += 1 print("sum is", sum) # print the sum 

Output:

sum is 55


This while loop executes until i < 11. The variable sum is used to accumulate the sum of numbers from 0 to 10. In each iteration, the value is i is added to the variable sum and i is incremented by 1. When i becomes 11, loop terminates and the program control comes out of the while loop to execute the print() function in line 7.

Inside the body of the while loop you should include a statement which alters the value of the condition, so that the condition eventually becomes false at some point. If you don't do this then you will encounter an infinite loop - a loop which never terminates.

Suppose we had mistakenly written the above program as follows:

python101/Chapter-10/an_infinite_loop.py

 1 2 3 4 5 6 7 8 i = 1 sum = 0 while i < 11: print(i) sum += i i += 1 print("sum is", sum) 

Here the statement i += 1 is outside the body of the loop which means value of i will never be incremented at all. As a result, the loop is infinite because the the condition i < 11 is true forever. Try executing above program and you will find that it will keep printing the value of i indefinitely.

Output:

 1 2 3 4 5 6 1 1 1 1 1 ... 

An infinite loop usually ends when system runs out of memory. To stop a infinite loop manually hit Ctrl + C.

However, this doesn't means that infinite loops are useless. There are some programming tasks where infinite loop really shines. Consider the following example:

Example 3: Program to calculate temperature from Fahrenheit to Celsius.

python101/Chapter-10/fahrenheit_to_celsius.py

  1 2 3 4 5 6 7 8 9 10 11 12 keep_calculating = 'y' while keep_calculating == 'y': fah = int(input("Enter temperature in Fahrenheit: ")) cel = (fah - 32) * 5/9 print(format(fah, "0.2f"), "°F is same as", format(cel, "0.2f"), "°C") keep_calculating = input("\nWant to calculate more: ? Press y for Yes, n for N: ") print("Program Ends") 

When you run the program it will ask you to enter a temperature in Fahrenheit. It then converts the temperature in Fahrenheit to Celsius and displays the result. At this point, program will ask you "Want to calculate more: ?". If you enter y, it will again prompt you to enter temperature in Fahrenheit. However if you press n or any other character the loop terminates and the program control comes out of the while loop and prints "Program Ends" to the console.

Output:

 1 2 3 4 5 6 7 8 9 Enter temperature in Fahrenheit: 43 43.00 °F is same as 6.11 °C Want to calculate more: ? Press y for Yes, n for N: y Enter temperature in Fahrenheit: 54 54.00 °F is same as 12.22 °C Want to calculate more: ? Press y for Yes, n for N: n Program Ends 

## The for loop #

In Python, we use for loop to iterate though a sequence.

So what is sequence ?

A sequence is a generic term which refers to data of following types:

• string
• list
• tuples
• dictionary
• set

Note: We have only covered strings at this point, the rest of the types will be discussed later.

The syntax of the for loop is as follows:

 1 2 3 4 5 6 for i in sequence: # loop body ... 

The first line in the syntax i.e for i in sequence: is known as for clause. In the next line, we have indented block of statements which executes everytime the loop iterates.

Suppose the sequence is a list [11, 44, 77, 33, 199], then the code to iterate through the list can be written as:

 1 2 3 4 5 6 for i in [11, 44, 77, 33, 199]: # loop body ... 

Note: In Python, a comma separated list of values inside square brackets [] is known as list. We will discuss list in detail in lesson Lists in Python.

Here is how it works:

In the first iteration value 11 from the list is assigned to the variable i, then the statement inside body of the loop is executed. This completes the first iteration of the loop. In the second iteration next value from the list i.e 44 is assigned to the variable i, then again statements inside the body of the loop is executed again. The same process repeats for next values. The loop terminates when the last value i.e 199 from the list is assigned to variable i and loop body is executed. The program control then comes out of the loop to begin execution of statements following it.

Here are some examples:

Example 1: for loop which iterates through the elements in a list

  1 2 3 4 5 6 7 8 9 10 >>> >>> for i in [11, 44, 77, 33, 199]: ... print(i) ... 11 44 77 33 199 >>> 

Example 2: for loop which iterates through the characters in a string

  1 2 3 4 5 6 7 8 9 10 >>> >>> for i in "astro": ... print(i) ... a s t r o >>> 

## for loop with range() function #

In addition to iterating over sequences, we also use for loop, when we know in advance how many times loop body needs to be executed. Such loops are known as count-controlled loops. Python provides a function called range() which eases the process of creating count-controlled loops. The range() function returns an object of special type know as iterable. Just as a sequence, An iterable object returns a successive items from a desired sequence when we iterate over it. You can think of iterable object, just as list, but it is not an actual list though.

At its simplest, the syntax of the range() function is:

range(a)


where a is an int.

The range(a) returns a sequence of integers from 0 to a-1.

Here is the code to create a for loop which executes it's loop body 5 times:

  1 2 3 4 5 6 7 8 9 10 >>> >>> for i in range(5): ... print(i) ... 0 1 2 3 4 >>> 

In the above code, range(5) returns a sequence of numbers from 0 to 4. In the first iteration range(5) function returns 0, which is then assigned to variable i. Then the loop body is executed. In the second iteration range(5) returns 1, which is then assigned to variable i. The loop body is executed again. The loop terminates when 4 is assigned to variable i and loop body is executed.

The above code is equivalent to:

  1 2 3 4 5 6 7 8 9 10 >>> >>> for i in [0, 1, 2, 3, 4]: ... print(i) ... 0 1 2 3 4 >>> 

The range() function has following two more versions:

1. range(a, b)
2. range(a, b, c)

### range(a, b) #

The range(a, b) returns a sequence of of the form a, a+1, a+2, ... b-2, b-1.

For example: range(90, 100) returns a sequence a sequence of number from 90 to 99.

### range(a, b, c) #

By default, the range() function returns a sequence of numbers where each successive number is greater than it's predecessor by 1. If you want to change that pass a third argument to the range() function. The third argument is know as step value. For example:

The range(0, 50, 5) returns the following sequence of numbers:

0, 5, 10, 15, 20, 25, 30, 35, 40, 45


Notice that each number is separated from one another by 5.

Here are some examples:

Example 1:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 >>> >>> for i in range(10, 20): ... print(i) ... 10 11 12 13 14 15 16 17 18 19 >>> 

Example 2:

 1 2 3 4 5 6 7 8 9 >>> >>> for i in range(10, 20, 3): # step value is 3 ... print(i) ... 10 13 16 19 >>> 

We can also specify a negative step value:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 >>> >>> for i in range(50, 0, -5): ... print(i) ... 50 45 40 35 30 25 20 15 10 5 >>> 

The following program uses for loop to generate squares of numbers from 1 to 20:

python101/Chapter-10/squares_from_1_to_20.py

 1 2 3 4 5 print("Number\t | Square") print("--------------------") for num in range(1, 21): print(num, "\t\t | ", num*num) 

Output:

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 Number | Square -------------------- 1 | 1 2 | 4 3 | 9 4 | 16 5 | 25 6 | 36 7 | 49 8 | 64 ... 17 | 289 18 | 324 19 | 361