Sometimes we may need to alter the flow of the program. If the execution of a specific code may need to be repeated several numbers of times then we can go for loop statements.
For this purpose, the python provide various types of loops which are capable of repeating some specific code several numbers of times. Those are,
With the while loop we can execute a set of statements as long as a condition is true. The while loop is mostly used in the case where the number of iterations is not known in advance.
Syntax:while expression:
Statement(s)
i=1;
while i<=3:
print(i);
i=i+1;
1
2
3
Python enables us to use the while loop with the else block also. The else block is executed when the condition given in the while statement becomes false.
Syntax:while expression:
Statements
else:
Statements
i=1;
while i<=3:
print (i)
i=i+1;
else: print("The while loop terminated");
1
2
3
The while loop terminated
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.
Syntax:for iterating_var in sequence:
statement(s)
i=1
n=int(input("Enter n value : "))
for i in range(i,n+1):
print(i,end = ' ')
Enter n value: 5
1 2 3 4 5
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.
Syntax:for iterating_var in sequence:
statements
else:
statements
for i in range(0,5):
print(i)
else:
print("for loop completely exhausted");
0
1
2
3
4
for loop completely exhausted
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:
range(6) means the values from 0 to 5.
range(2,6) means the values from 2 to 5.
i=1;
num = int(input("Enter a number:"));
for i in range(1,11):
print("%d X %d = %d"%(num,i,num*i))
Enter a number: 10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
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.
Syntax:for iterating_var1 in sequence:
for iterating_var2 in sequence:
#block of statements
n = int(input("Enter the no.of rows you want to print : "))
for i in range(0,n):
for j in range(0,i+1):
print("*",end="")
print()
Enter the no.of rows you want to print: 4
*
* *
* * *
* * * *