for

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.

snippet
for iterating_var in sequence:
	statement(s)
Python for loop

Example

snippet
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 = ' ')

Output:

Output
0 1 2 3 4 5 6 7 8 9

Python for loop example : printing the table of the given number

snippet
i=1;
num = int(input("Enter a number:"));
for i in range(1,11):
    print("%d X %d = %d"%(num,i,num*i));

Output:

Output
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.

snippet
for iterating_var1 in sequence:
	for iterating_var2 in sequence:
		#block of statements 
#Other statements

Example 1

snippet
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="")

Output:

Output
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.

Example 1

snippet
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.

Output:

Output
0 1 2 3 4

for loop completely exhausted, since there is no break.

Example 2

snippet
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.

Output:

Output
0

The loop is broken due to break statement...came out of loop

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents