# Python while Loop

What is while loop in Python? Python consists of two types of loops, namely for loop and while loop. A while loop is categorized as a kind of indefinite iteration. This basically means that in a python while loop, we cannot predict the number of times it will be executed. It can sometimes even be thought of as a reiterating if statement. Let us discuss the while loop in detail.

The main function of a while loop in python is to repeatedly execute a block of code statements as long as the test condition/expression is satisfied(true). The next line in the program will only be executed once the test condition/expression becomes false.

#### Syntax:

In this, the first step is to check the test expression.

                    
while test:
statement(s) within the loop



Statement(s) within the loop includes all those statements which are indented by the same number of spaces on the left. These statements are collectively referred to as a single code block. Python employs indentation for the grouping of statements and the end of a block of code is determined by the first unindented line. By default, any non-zero value is determined as true whereas None and 0 are interpreted as

                    
False



### How do you use a while loop in Python?

#### Example:

                    
#introducing while loop
#program to multiply
#numbers upto n
a = 5

#Initilizing sum and counter variables
prod = 0
count = 1

while(count<a):
a+=1
prod = prod*count
count+=1  #incrementing counter value by one after each iteration

#print the result
print("The product is", prod)

print()



#### Output:

When the above program is run, the result obtained is as follows:

                    
Enter a:5
The product is 120



In the written program, the code will be executed(or the test expression will be

                    
True


as long as the counter variable stays less than or equal to
                    
a


i.e., 5 in our program.

The counter variable is incremented by one after each iteration and the statement for the same has been defined in the body of the while loop. This is a crucial step, yet most of the students and learners tend to miss this step and then end up with infinite loops (loops that do not terminate on their own).

### How does a Python While loop work?

Source: wikipedia

### Loop Control Statements

To change the execution of loops from their normal sequence, loop control statements are used. And, if there is any scope left after the execution of the given statements, every automatic object created within that scope is deleted. Here are some of the control statements supported by Python:

• Break Statement

This statement is used whenever we need to stop the execution of the program even though the condition of the while loop is

                    
True


To get a better understanding of this, let us take a gander at the example below:

                    
list = [1,25,37,4,85,6,17,58,9]
i=0
while (i < 4):
print (list[i])
i+=1
if (i==5):
break




Output:

                    
1
25
37
4
85



In this program, we first defined a list of random numbers and then we started the counter variable. The while loop is executed either as long as the number of iterations is equal to or less than 4 or if the  5th element in the list is reached. In the case of the latter, break statement is used to terminate the loop when the value of the variable

                    
i


is 3.

#### Continue Statement

With the help of the continue statement, the control is returned to the beginning of the loop. Let us see this with an example.

                    
#Program to print all letters in mississippi except 's' and 'i'
a = 0
b = 'mississippi'

while a < len(b):
if b[a]== 's' or b[a] == 'i':
a+=1
continue
print (The current letter is : ", b[a])
a+=1



Output:

The result obtained on execution of the above program is:

                    
The current letter is : m
The current letter is : p
The current letter is : p



On successful execution of the program, all the letters except ‘i’ and ‘s’ are returned to the screen as output. Each iteration takes the entire word ‘mississippi’ into account and prints the first letter after eliminating ‘i’ and ‘s’. Hence, the first letter that is printed is m and then p is printed twice since it occurs twice in the selected word.

• Pass Statement

When there is a need for creating empty loops, we make use of the pass statement. Pass statement is also used in empty control statements, functions and classes. Again, let us see this with an example.

                    
#Creating an empty loop
a = 'Hello World'
i=0

while i <= len(a):
i+=1
pass
print("The value of i is: ', i)



Output:

The result obtained on execution of the above program is:

                    
The value of i is : 10



In the above program, we need to crate an empty loop in which we store all the values of the string ‘Hello World’. Next, a counter variable

                    
i


is started. For this, we use the len() function for calculating the number of letters in the current string. While loop is defined such that it displays the precise number of letters in the string. The counter variable is incremented by one for each iteration as long as all the letter in the string is taken into account while executing the program.

### While loop with else

Similar to for loops, while loops also have an optional else block. This else block is executed only when the test condition/expression results in

                    
False



As discussed above, we can make use of a break statement to terminate a while loop. The else block is ignored in such cases. Therefore, the else block of a while loop runs if the program is executed without any breaks and the condition/expression is false. In other words, we have already learnt that the line immediately after the loop is executed in case the condition becomes false which is precisely the case here.

                    
#Write a code to show how
#the while-else loop works when executed
i = 0
while i < 6:
i+=1
print (i)
#since there is no break statement,
#else block will be executed
else:
print ("No Break/n")


                    
#Write a code to show how the
#while-else loops work with break
i = 0
while i < 6:
i+=1
print (i)
break
else: #here the else block will be ignored
print ("No Break")




Output:

                    
1
2
3
4
5
No Break

1



## FAQs on Python while loop

Q. Is there a while loop in Python?

A. Yes, there are two kinds of loops in Python- for loop and while loop.

Q. How do you write a while loop in Python?

A. The syntax for a while loop is as follows:

                    
while test:
statement(s) within the loop



Q. How does while loop work in Python?

A. The main function of a while loop in python is to repeatedly execute a block of code statements as long as the test condition/expression is satisfied(true). The next line in the program is executed only once the test condition/expression becomes false.

Q. How do you use a while loop?

A. The while loop first evaluates the test condition/expression. The text expression is executed as long as the condition remains true. The loop is terminated once the test expression is false.

Share with friends

## Customize your course in 30 seconds

##### Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
Ashhar Firdausi
IIT Roorkee
Biology
Dr. Nazma Shaik
VTU
Chemistry
Gaurav Tiwari
APJAKTU
Physics
Get Started

Subscribe
Notify of