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)
i=1 n=int(input("Enter the number up to which you want to print the natural numbers?")) for i in range(0,10): print(i,end = ' ')
Python for loop example : printing the table of the given number
i=1; num = int(input("Enter a number:")); for i in range(1,11): print("%d X %d = %d"%(num,i,num*i));
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.
for iterating_var1 in sequence: for iterating_var2 in sequence: #block of statements #Other statements
n = int(input("Enter the number of rows you want to print?")) i,j=0,0 for i in range(0,n): print() for j in range(0,i+1): print("*",end="")
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.
for i in range(0,5): print(i) else:print("for loop completely exhausted, since there is no break.");
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.
for loop completely exhausted, since there is no break.
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 loop")
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