Python provide three ways for executing the loop , For loop is one of them. For loops are used for sequential traversal. If we want to iterate over natural numbers , we can make a list of the number or we can use Range keyword.
For Loop in Python
A for loop is used to iterate over a sequence (such as a list, tuple, string, or range) and execute a block of code for each item in the sequence.
#python program to illustrate for loop
list=[1,2,3,4]
for i in list: # i will acquire the value's in the list one by one
print(i,end=' ')
print('')
x={'A':1,'B':2}
for i in x.keys(): # i will have the values of key of the dictionary
print(x[i] , end=' ')
print('')
# if we want to iterate over natural number from 0 to 5
n=5
for i in range(n+1): # loop will run 6 times for 0 1 2 3 4 5
print(i,end=' ')
print('')
#for loop from 2 to 5
n=5
for i in range(2,n+1):
print(i,end=' ')
print('')
#loop with incremenation=2
n=12
for i in range(2,n,2): #all the even numbers from 2 to 11
print(i, end=' ')
print('')
#loop from n to 0
n=5
for i in range(n,-1,-1): # loop from n to -1 (excluding) with rate of -1 (we can change the rate to -2 or -3)
print(i,end=' ')
print('')
#nested for loop
for i in range(2):
for j in range(2): # loop will rum 2*2 = 4 times
print(i , end=' ')
print('')
Login/Signup to comment