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.
0 1 2 3 4 5 6 7 8 9
Python for loop example : printing the table of the given number
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
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 of the nested for loop in python is given below.
Enter the number of rows you want to print?5 * ** *** **** *****
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.
In the above example, for loop is executed completely since there is no break statement in the loop. The control comes out of the loop and hence the else block is executed.
0 1 2 3 4
for loop completely exhausted, since there is no break.
In the above example, the loop is broken due to break statement therefore the else statement will not be executed. The statement present immediate next to else block will be executed.
The loop is broken due to break statement...came out of loop