Learn Python Programming

The for Loop


for loop allows the execution of statement or a group of statement multiple times. The for loop is useful to iterate over the elements of a sequence. The for loop can iterate with sequence like string, list, tuple, range etc. In order to enter the loop, there are the certain conditions defined in the beginning. Once the condition becomes false the loop stops and the control moves out of the loop.

Python for loop statement Flowchart:

Syntax

for var in sequence:
		statements

The first statement of the sequence is assigned to a variable written after ‘for’ and then the statements are executed. Next, the second element of the sequence is assigned to the variable and then the statements are executed second time. In this way, for each element of the sequence, the statements are executed once. So, the for loop is executed as many times as there are number of elements in the sequence.

Example: Python for Loop

A Python program to display characters of a string using for loop.

str='Hello'
for ch in str:
		print(ch)

#Output:
H
e
l
l
o

A Python program to display odd numbers from 1 to 10 using range().

for i in range(1,10,2):
		print(i)

#Output:
1
3
5
7
9