Python while loop

In this article you will learn about python while loop which is used to repeat specific block of code or iterate over a block repeatedly until the condition become true.

What is while loop in Python?

The while loop in python is used to iterate over a specific block of code as long as condition become true.

This loop is generally used when when we don’t know how many number of times this loop will repeat beforehand.

Syntax

While Condition:
   Body of while loop

In while loop, condition is checked first. If the condition is true than only the body of loop entered. The condition is check again and again after one iteration. The process of iteration continue until the condition become to false.

The indentation is use for determination the body of while loop.

Python interpreters interprets any none-zero value like 1,2,3 as True and zero(0), none as False.

Examples: Python while loop

#Program to add sum of number
n=10
#intialization sum and count
sum=0
i=5
while i<=n:
   sum=sum+i
   i=i+1       #update counter
#print the sum
print("the sum is ",sum)

When you run the program output will be

The sum is 15

In above program, condition will true until counter variable i is less than or equal to 10.

We need to increase the value of counter variable this is very important because failing to do will result in infinite loop means loop will never end.

While loop with else

While loop can also use else block as optional block. It execute when the condition of while loop evaluate to false or when the while loop complete it’s execution.

we can use break keyword to terminate while loop, in such case else part is ignored.

Here is the example to explain this,

Counter=0
while counter<2:
   print("Inside loop")
   counter=counter+1
else:
   print("Inside else")

Output

Inside loop
Inside loop
Inside else

Here to print string we used counter variable inside loop two times. On the third iteration condition become false and else part is executed.

For more detail learning i python visit python official sites Python.org.

Was this article helpful?
YesNo

Leave a Comment