Python for loop

The for loop is useful to iterate over the elements of a sequence. It means, the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the sequence.

The for loop can work with sequence like string, list, tuple, range etc.

The syntax or format of for loop is:

CopiedCopy Code

for var in sequence:
	statements

The first element of the sequence is assigned to the 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.

for loop examples:

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

CopiedCopy Code

#to display each character from a string 
str='Hello' 
for ch in str: 
    print(ch)

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

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

A Python program to display each character from a string using sequence index.

CopiedCopy Code

#to display each character from a string 
str='Hello' 
n = len(str) #find no. of chars in str
for i in range(n): 
   print(str[i])							
							

Write a program to display numbers from 10 to 1 in descending order.

CopiedCopy Code

for x in range (10, 0, -1): 
   print(x)

Write a program to display the elements of a list using for loop.

CopiedCopy Code

list = [10,20.5,'A','Anantapur'] 
for element in list: 
     print(element)


Write a Python program to display and find the sum of a list of numbers using for loop.
CopiedCopy Code

list = [10,20,30,40,50] 
sum=0 
for i in list: 
  print(i) 
  sum+=i
print('Sum=', sum)