While Loop in Python with example

Updated: Feb 17


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



19 views0 comments

Recent Posts

See All

Tell () function can be used to get the position of file handle and returns current position of file object where as Seek () function is used to change the position of the file handle to a given speci

Seek () function is used to change the position of the file handle to a given specific position in python. File handle such as a cursor which defines from where the data has to be read or written in t