• Articles
  • Tutorials
  • Interview Questions

Python While Loop

Tutorial Playlist

Table of content

Show More

Introduction to Python While Loop

As discussed in the previous module, we know that Python, like other top programming languages, consists of some control flow statements. One of the control flow statements that we have already studied in the previous module is the Python if else statement. Another one of the control flow statements is loops. Loops are used when we want to repeat a block of code a number of times. In this module, we will learn about Python while loop.

So, without any further delay, let’s get started.

What is a While Loop in Python?

While loop statements in Python are used to repeatedly execute a certain statement as long as the condition provided in the while loop statement stays true. While loops let the program control to iterate over a block of code.

Syntax for While Loop in Python:

while test_expression:
body of while

The following flowchart explains the working of the while loop in Python.

python while loop

The program first evaluates the while loop condition. If it’s true, then the program enters the loop and executes the body of the while loop. It continues to execute the body of the while loop as long as the condition is true. When it is false, the program comes out of the loop and stops repeating the body of the while loop.

Let’s see the following example of Python while loop to understand it better.

a = 1


while( a<10):
print(” loop entered”, a, “times”)
a = a+1
print(“loop ends here”)


Output:
loop entered 1 times
loop entered 2 times
loop entered 3 times
loop entered 4 times
loop entered 5 times
loop entered 6 times
loop entered 7 times
loop entered 8 times
loop entered 9 times
loop ends here

Interested in learning Python? Enroll in our Python Course in London now!

Get 100% Hike!

Master Most in Demand Skills Now!

Flowchart of Python While Loop

A while loop in Python repeats as long as a condition is true. Here is the basic syntax with an example:

while condition:

statement(s)

For example:

counter = 0

while counter < 5:

print(counter)

counter = counter + 1

This prints the numbers 0 to 4.

The flowchart below shows each step:

  1. The condition counter < 5 is first checked before entering the loop. This verifies if the counter variable is less than 5.
  2. If true, the code inside the loop runs – it prints the value of the counter
  3. After printing, the counter is incremented by 1 with counter = counter + 1.
  4. Python returns to the top to re-check the condition.
  5. It continues looping and printing until the condition becomes false when the counter reaches 5.
  6. Once counter >= 5, the program exits the while loop and continues with any code after it.

Infinite While Loop in Python

Infinite while loop refers to a while loop where the while condition never becomes false. When a condition never becomes false, the program enters the loop and keeps repeating that same block of code over and over again, and the loop never ends.

The following example shows an infinite loop:

a = 1


while a==1:
b = input(“what’s your name?”)
print(“Hi”, b, “, Welcome to Intellipaat!”)

If we run the above code block, it will execute an infinite loop that will ask for our names again and again. The loop won’t break until we press ‘Ctrl+C’.

Output:

what’s your name?
Akanksha Rana #user input
Hi Akanksha Rana , Welcome to Intellipaat!


what’s your name?
Amrit #user input
Hi Amrit , Welcome to Intellipaat!


what’s your name?
Shubham #user input
Hi Shubham , Welcome to Intellipaat!


what’s your name?
Traceback (most recent call last): #Stopped the loop by entering CTRL+C
File “”, line 2, in
KeyboardInterrupt

Become a Python Expert

Python Do While Loop

Python doesn’t have a do-while loop. But we can create a program to implement do-while. It is used to check conditions after executing the statement. It is like a while loop but it is executed at least once.

i = 1  
while True:  
print(i)  
    i = i + 1  
    if(i > 5):  
        break  

The output will be
1
2
3
4
5

Now, take a look at our Python training for upgrading your career to new heights. Also, check out our free Python programming Interview Questions.

Python While True Loop

There is a concept of declaring a condition to be true, without evaluating any expression. This is done to indicate that the loop has to run until it breaks. We then write the break statements inside the code block.

The while true in python is simple to implement. Instead of declaring any Python variable, applying conditions, and then incrementing them, write true inside the conditional brackets.

weeklySalary = 0
dayOfWeek = 1
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
while(True):
    if(week[dayOfWeek] == "Sunday"):
        print("Holiday!!")
        break
    weeklySalary += 2000
    dayOfWeek += 1 
print(str(weeklySalary))

The output will be 
Holiday!!
10000

Python While Loop with Else 

In Python, we can also use the else statement with loops. When the else statement is used with the while loop, it is executed only if the condition becomes false.

a = 1

while a<5:
print(“condition is true”)
a=a+1

else:
print(“condition is false now”)

The example illustrates how the else statement works with the while loop.

Output:

condition is true
condition is true
condition is true
condition is true
condition is false now

In the above example, the program keeps executing the body of the while loop till the condition is true, meaning that the value of a is less than 5. Since the initial value of a is 1 and every time the program enters the loop the value of a is increased by 1, the condition becomes false after the program enters the loop for the fourth time when the value of a is increased from 4 to 5. When the program checks the condition for the fifth time, it executes it as false and goes to the else block and executes the body of else, displaying, ‘condition is false now.’

Watch this video on ‘Python Tutorial’:

Video Thumbnail

Kick-start your career in Python with the perfect Python Course in New York now!

Python While Loop Interruptions

Python offers the following two keywords which we can use to prematurely terminate a loop iteration.

Break statements in While loop

  1. Break: The break keyword terminates the loop and transfers the control to the end of the loop.
Example:
a = 1
while a <5:
a += 1
if a == 3:
break
print(a)
Output:
2

Continue statements in While loop

  1. Continue: The continue keyword terminates the ongoing iteration and transfers the control to the top of the loop and the loop condition is evaluated again. If the condition is true, then the next iteration takes place.

Example:

a = 1
while a <5:
a += 1
if a == 3:
continue
print(a)

Output:
2
4
5

Go for the most professional Python Course Online in Toronto for a stellar career now!

Examples of Python While Loop

The examples given below demonstrate various use cases of the While loops in Python. Remember to choose the appropriate loop structure based on your specific needs and ensure proper indentation for clear and efficient code. Here are some common examples:

 

Summing Values

 

total = 0

number = int(input(“Enter a number (0 to quit): “))

while number != 0:

total += number

number = int(input(“Enter a number (0 to quit): “))

print(“Total is:”, total)

We keep summing numbers entered by the user until they enter 0.

 

Number Pattern Program in Python using While Loop 

n = int(input(“Enter the number of rows: ”))
i = 1
while i <= n:
    j = 1
    while j <= i:
        print(“*”, end = “ ”)
        j += 1
    print()
    i += 1

The output will be
Enter the number of rows: 4
*
**
***
****

Factorial Program in Python using While Loop

num = int(input("Enter a number: "))
fac = 1
i = 1
while i <= num:
    fac = fac * i
    i = i + 1
print("Factorial of ", num, " is ", fac)

The output will be
Enter a number: 4
Factorial of  4  is  24

With this, we come to the end of this module on Python Tutorial. You can also go through this Python Data Science tutorial to know why Python is the most preferred language for Data Science. Also, check out our free Python Programming Interview Questions.

 

Course Schedule

Name Date Details
Python Course 23 Nov 2024(Sat-Sun) Weekend Batch View Details
30 Nov 2024(Sat-Sun) Weekend Batch
07 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.