While Loop in Python
while loop is used to execute a block of
statements repeatedly until condition does not satisfy.
When
condition becomes false the statements written in block will get execute.
Syntax:
while expression:
statement(s)
In the above syntax statement may be single
or multiple statements. The test condition may have any condition. The while
loop will get iterate again and again until condition doesnot satisfy.
In
Python all the statements indented by the same number of characters and spaces
after the block.
For example:
In above example first 10 numbers are displayed on screen by using while loop.
First i is initialized with 0 and then it is repeatedly executed until final result does not meet.
Once condition becomes false i.e. when get 11 the iteration will stop and execute related statement.
In every iteration the number will be incremented by 1.
# Sum of n natural numbers using while loop
n=int(input("Enter Namer\t"))
sum=0
i=1
while i<=n :
sum=sum+i
i=i+1
print(sum)
O/P:
Enter Namer 10
1
3
6
10
15
21
28
36
45
55
# Sum of n even natural numbers using while loop
n=int(input("Enter Namer\t"))
sum=0
i=1
print("The sum of n even numbers
is:\t")
while i<=n :
if
i%2==0:
sum=sum+i
i=i+1
print(sum)
O/P:
Enter Namer
10
The sum of n even numbers is: 30
# Fibonacci Series using while loop
n=int(input("Enter number to display fibonacci series\t"))
a=0
b=1
i=1
c=0
while i<=n:
i=i+1
a=b
b=c
c=a+b
print(c)
O/P:
Enter number to display fibonacci series 10
1
1
2
3
5
8
13
21
34
55
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏