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

Files MCQ in Python

File Processing MCQ Q1. Which function writes a list of lines in File? A.      Writelines() B.      Write() C.      Tell() D.      All of...

Python List MCQ Questions

Q1. What is output of below python code? dict= {1:'1', 2:'2', 3:'3'} del dict[1] dict[1] = '10' del dict[2] print (len(dict)) A. 1 B. 2...

Python NUMPY MCQ Questions

Python NumPy Chapter MCQ: 1. What will be print? Import numpy as np a = np. array([1,2,3,5,8]) b = np. array([0,3,4,2,1]) c = a+b c = c*a...

Comments


bottom of page