While Loop in Python

Updated: May 18


While loop is used to iterate over a block of code again and again until a given condition returns false. A program is executed repeatedly when condition is true. If condition is not true then program is not execute. The given condition is false, the loop is terminated and the control jumps to the next statement in the program after the loop and if the condition returns true, the set of statements inside loop are executed and then the control jumps to the beginning of the loop for next iteration.

Syntax:

while condition:

statements

The statements are set of Python statements which require repeated execution. These set of statements execute repeatedly until the given condition returns false.

Example:

a = 1

while a < 7:

print(a)

a = a + 2

Output:

1

3

5

Infinite while loop

a = 2

while a<5:

print(a)

Nested while loop in Python

When a while loop is present within another while loop then it is called nested while loop.

i = 1

j = 5

while i < 5:

while j < 9:

print(i, ",", j)

j = j + 1

i = i + 1

Output:

1 , 5

2 , 6

3 , 7

4, 8

While loop with else block

n= 9

while n > 5:

print(n)

n = n-1

else:

print("loop is finished")

Output:

9

8

7

6

loop is finished