You are on page 1of 5

TOPIC : WHILE LOOP IN PYTHON

while loop
A while loop is a conditional loop that will repeat the instructions within itself as
long as a condition remains true.
Syntax:
while <logical expression>:
Block of Statement
Examples:

n=1 Output:
while n<5: 1
print(n*n) 4
n+=1 9
16
print(“Thank You”)
Thank You
a=7 Output:
while(a>1): 7
print(a) 4
a-=3 End of loop
print(“End of loop”)
Important points that you need to know related to while loop
 In while loop, a loop control variable should be initialized before the loop begins.
Otherwise it will display error because an uninitialized variable can not be used in an
expression.
Example:
while p<10:
print(p)
p=p+3
 The loop variable must be updated inside the body of loop in such a way that after
some time the test condition becomes false otherwise the loop become an endlessloop
i.e. infinite loop.
Example:
p=5 p=5
while p>1: while p>1:
print(p) print(p)
p-=1
Note: This is infinite loop Note: Here loop variable p is updated
while loop Programs
Program 1: To find factorial of a number entered by user.

n=int(input(“Enter any number”))


f=1
while n>0:
f=f*n
n=n-1
print(“Factorial of entered number =“,f)

n=4
=4*3*2*1=24
while loop Programs
Program 2: To find sum of even and odd numbers of first n natural
numbers entered by the user.
n=int(input(“Enter any number”))
c=1
ev=odd=0
while c<=n:
if c%2==0:
ev = ev+c
else:
odd = odd+c
c=c+1
print(“Sum of even integers =“,ev)
print(“Sum of odd integers =“,odd)

You might also like