- while loop
- 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
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:-
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:-
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:-
- How to use search and replace functions in python with examples
- How to use split(),count(),partition and join functions in python
- Operators in python with real examples
- Print function complete knowledge in python with examples
- Literal in python with examples
- Learn Complete History of python with examples
- Algorithm concepts in python with examples
Watch Complete Lecture Video:-
0 comments:
Post a Comment