top of page
Writer's pictureRajesh Singh

While Loop in Python with example

Updated: Feb 17, 2022


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.


"In general way the while loop statement is a conditional loop which repeats a program and any part of it until a given condition is true."

Syntax:

while condition:

statement

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

Write a program to print 10 even numbers in reverse order.

Program:

a=20

while a>=2:

print(a)

a=a-2

Output:

20

18

16

14

12

10

8

6

4

2

To print 10 even numbers in reverse order Video in Python:




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



Recent Posts

See All

Comments


bottom of page