while loops are extremely similar to the for loops, in for loops the iterations are normal (one after another without any condition )
a while loop can be understand as conditional loop i.e till the time the condition is going to be true loop is going to iterate ;
we usually use while loop when we don't know the starting and end points i.e " number of times the loop is going to iterate "
for example :
Q. print "my name" 10 times using for while loop .
n = 10
i = 1
while i <= n : # condition if true then my name will be printed else not
print("my name ")
i += 1 # every time value of i will be incremented by 1
Q. print sum of first 10 numbers using while loop
n = 10
i = 1
sum = 0
while i <= n :
sum = sum + i # every time previous number get added
print("the sum till ",i, ":", sum)
i = i+1
a while loop can be understand as conditional loop i.e till the time the condition is going to be true loop is going to iterate ;
we usually use while loop when we don't know the starting and end points i.e " number of times the loop is going to iterate "
for example :
Q. print "my name" 10 times using for while loop .
n = 10
i = 1
while i <= n : # condition if true then my name will be printed else not
print("my name ")
i += 1 # every time value of i will be incremented by 1
output:
Q. print sum of first 10 numbers using while loop
n = 10
i = 1
sum = 0
while i <= n :
sum = sum + i # every time previous number get added
print("the sum till ",i, ":", sum)
i = i+1
output:


Comments
Post a Comment