How to use for loop repetition control in python with examples

By
For loop is used to iterate over elements of a sequence such as string,tuple,list and dictionary etc.
For loops are used for sequential traversal. 
For loop has two forms:-
1.)  for var in list:
         statement 1
         statement 2
         statement 3


2.) for var in list:
        statement 1
        statement 2
      else:
          statement 3
          statement 4
Note:-
  • During each iteration var is assigned the next value from the list.
  • else block is executed when items in the list get exhauted.
  • A for loop can be used to generate a list of numbers using the built-in range() functions.
  • range(10)--> Generates numbers from 0 to 9.
  • range(10,20)--> Generates numbers from 10 to 19.
  • range(10,20,2)--> Generates numbers from 10 to 19 in steps of 2.
  • range(20,10,-3)--> Generates numbers from 20 to 11 in steps of -3.
Program 1:Write a program to print the 10 numbers in python.
i=0
num=10
for i in range(i,num):
    print(i)
Output:-

Program 2:Write a python program to print the numbers upto which user want to print.
i=1
num=int(input("enter the number:\n"))
for i in range(0,num):
    print(i,end="")
Output:-
Program 3:Write a program to print the even numbers upto 20 numbers in python.
i=2
num=20
for i in range(0,num,2):
    print(i)
Output:-

Nested for loop in python:-
  • Python allows us to use nested for loop inside your python program.
  • The inner for loop is executed first where for every iteration of the outer for loop.
Syntax:-
for var1 in list1:
     for var2 in list2:
          statement 1
          statement 2
    statement 3
    statement 4

Program 4:Write a program to print the star(*) triangle in python.
i=0
j=0
num=int(input("Enter the number of row which you want to print: \n"))
for i in range(0,num):
    print(" ")
    for j in range(0,i+1):
        print("*", end=" ")

Output:-

How to use else statement in for loop?:-
  • Python allows us to use the else statement with the for loop.
  • This else statement will be executed only when all the iterations are exhausted.
  • If for loop contains break statement then the else statement will not be executed.
Program 5:Write a program to print the natural numbers in decreasing order in python.
i=0
num=int(input("Enter the number:\n"))
for i in range(num,0,-2):
    print(i,end=" ")
else:
    print("else statement is running")
Output:-
Program 6:Write a program to print the natural numbers in increasing order using break statement in python.
i=0
num=int(input("Enter the number:\n"))
for i in range(0,num,2):
    print(i,end=" ")
    if(i==8):
        break
else:
    print("else statement is running")
Output:-
For More...
Watch complete Lecture Video:-


0 comments:

Post a Comment

Powered by Blogger.