Python Loops
The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific code
may need to be repeated several numbers of times.
Why we use loops in python?
The looping simplifies the complex problems into the easy ones. It enables us to alter the
flow of the program so that instead of writing the same code again and again, we can
repeat the same code for a finite number of times. For example, if we need to print the first
10 natural numbers then, instead of using the print statement 10 times, we can print inside
a loop which runs up to 10 iterations.
Advantages of loops
There are the following advantages of loops in Python.
1. It provides code re-usability.
2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked
lists).
There are the following loop statements in Python.
Loop Statement Description
for loop The for loop is used in the case where we need to execute some part of the
code until the given condition is satisfied. The for loop is also called as a per-
tested loop. It is better to use for loop if the number of iteration is known in
advance.
while loop The while loop is to be used in the scenario where we don't know the number of
iterations in advance. The block of statements is executed in the while loop until
the condition specified in the while loop is satisfied. It is also called a pre-tested
loop.
do-while loop The do-while loop continues until a given condition satisfies. It is also called post
tested loop. It is used when it is necessary to execute the loop at least once
(mostly menu driven programs).
Python for loop
The for loop in Python is used to iterate the statements or a part of the program several
times. It is frequently used to traverse the data structures like list, tuple, or dictionary.
The syntax of for loop in python is given below.
for iterating_var in sequence:
statement(s)
For loop Using Sequence
Example-1: Iterating string using for loop
str = "Python"
for i in str:
print(i)
Output:
Example- 2: Program to print the table of the given number .
list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)
Output:
10
15
20
25
30
35
40
45
50
Example-4: Program to print the sum of the given list.
list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)
Output:
The sum is: 183
For loop Using range() function
The range() function
The range() function is used to generate the sequence of the numbers. If we pass the
range(10), it will generate the numbers from 0 to 9. The syntax of the range() function is
given below.
Syntax:
range(start,stop,step size)
o The start represents the beginning of the iteration.
o The stop represents that the loop will iterate till stop-1. The range(1,5) will
generate numbers 1 to 4 iterations. It is optional.
o The step size is used to skip the specific numbers from the iteration. It is optional to
use. By default, the step size is 1. It is optional.
Consider the following examples:
Example-1: Program to print numbers in sequence.
for i in range(10):
print(i,end = ' ')
Output:
0123456789
Example - 2: Program to print table of given number.
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
Output:
Enter the number 10
10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100
Example-3: Program to print even number using step size in range().
n = int(input("Enter the number "))
for i in range(2,n,2):
print(i)
Output:
Enter the number 20
10
12
14
16
18
We can also use the range() function with sequence of numbers. The len() function is
combined with range() function which iterate through a sequence using indexing. Consider
the following example.
list = ['Peter','Joseph','Ricky','Devansh']
for i in range(len(list)):
print("Hello",list[i])
Output:
Hello Peter
Hello Joseph
Hello Ricky
Hello Devansh
The range() Function
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Example
Using the range() function:
for x in range(6):
print(x)
Output:
Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not
including 6):
Example
Using the start parameter:
for x in range(2, 6):
print(x)
Output
The range() function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 30, 3):
Example
Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Output
11
14
17
20
23
26
29
Nested for loop in python
Python allows us to nest any number of for loops inside a for loop. The inner loop is
executed n number of times for every iteration of the outer loop. The syntax is given below.
Syntax
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements
Example- 1: Nested for loop
# User input for number of rows
rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()
Output:
Enter the rows:5
**
***
****
*****
Example-2: Program to number pyramid.
rows = int(input("Enter the rows"))
for i in range(0,rows+1):
for j in range(i):
print(i,end = '')
print()
Output:
22
333
4444
55555
Using else statement with for loop
Unlike other languages like C, C++, or Java, Python allows us to use the else statement
with the for loop which can be executed only when all the iterations are exhausted. Here,
we must notice that if the loop contains any of the break statement then the else statement
will not be executed.
Example 1
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")
Output:
2
3
for loop completely exhausted, since there is no break.
The for loop completely exhausted, since there is no break.
Example 2
for i in range(0,5):
print(i)
break;
else:print("for loop is exhausted");
print("The loop is broken due to break statement...came out of the loop")
In the above example, the loop is broken due to the break statement; therefore, the else
statement will not be executed. The statement present immediate next to else block will be
executed.
Output:
The loop is broken due to the break statement...came out of the loop.
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output:
apple
banana
cherry
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry