How to use while loop repetition control in python with examples

By
There are two types of repetition control instructions in python.
  1. while loop
  2. for loop
1.) while Loop:
  • A while loop allows a part of code to be executed as long as the given condition is true.
  • The while loop is used to repeatedly execute instructions as long as expression is true.
  • A while loop is used in the case where the number of iterations is not know in advance.
The while loop has two syntax (forms):
a.) while condition:
         statement 1
         statement 2
         statement 3    

b.) while condition:
          statement 1
          statement 2
     else:
         statement 3
         statement 4

Note:-else block of codes will be executed when condition fails.
Program 1 : Write a python program to add the given numbers.
sum=0
num=int(input("Enter the last number upto which you want to add:\n"))
i=1
while(i<=num):
    sum =sum+i
    i=i+1
print("The sum of all numbers is= ",sum)
Output:-
Program 2 : Write a python program to print the given numbers.
num=int(input("Enter the number:"))
i=1
while(i<=num):
    print(i)
    i=i+1
Output:-

Infinite while loop:-
  • When any while loop condition never become false then while while loop will never terminate.This is called infinite condition.
  • Any non-zero values in while loop indicates always true condition and whereas zero indicates the always false condition.
Program 3 : While infinite loop:
num=int(input("Enter non zero number:"))
while(num):
    print("welcome to MNT LAB")
Output:-
Program 4 : While infinite loop:
import time
a=1
num=int(input("Enter a value:\n"))
while(1):
    n=a+num
    a=a+1
    time.sleep(2)
    print(n)
Output:-

Use the else statement in while loop:-
  • The else block is executed when the condition given in while loop becomes false.
  • If the while loop is terminated using break statement then else block of codes will not be executed and statement present after the else block will be executed.
Program 5 :Write a python program to print the list values.
list=[1,2,3,4,5,6,7,8,9,10]
i=0
while(i<10):
    print(list[i])
    i=i+1
Output:-

Program 6 : Write a python program to print the given numbers.
i=1
num=int(input("Enter the Number upto which you want to print: \n"))
while(i<=num):
    print(i)
    i=i+1
else:
    print("While loop is terminated...")
Output:-
Program 7 : Write a python program to print the some numbers out of given numbers.
i=1
num=int(input("Enter the Number upto which you want to print: \n"))
while(i<=num):
    print(i)
    if(i==8):
        break
    i=i+1
else:
    print("While loop is termineted...")

Output:-
For More...

0 comments:

Post a Comment

Powered by Blogger.