Recommended Video Course
Mastering While Loops
Table of Contents
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding:Mastering While Loops
Python’swhile
loop enables you to execute a block of code repeatedly as long as a given condition remains true. Unlikefor
loops, which iterate a known number of times,while
loops are ideal for situations where the number of iterations isn’t known upfront.
Loops are a pretty useful construct in Python, so learning how to write and use them is a great skill for you as a Python developer.
By the end of this tutorial, you’ll understand that:
while
is a Python keyword used to initiate a loop that repeats a block of code as long as a condition is true.while
loop works by evaluating a condition at the start of each iteration. If the condition is true, then the loop executes. Otherwise, it terminates.while
loops are useful when the number of iterations is unknown, such as waiting for a condition to change or continuously processing user input.while True
in Python creates an infinite loop that continues until abreak
statement or external interruption occurs.while True
loop with abreak
statement for conditional termination.With this knowledge, you’re prepared to write effectivewhile
loops in your Python programs, handling a wide range of iteration needs.
Get Your Code:Click here to download the free sample code that shows you how to work with while loops in Python.
Take the Quiz: Test your knowledge with our interactive “Python while Loops: Repeating Tasks Conditionally” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Python while Loops: Repeating Tasks ConditionallyIn this quiz, you'll test your understanding of Python's while loop. This loop allows you to execute a block of code repeatedly as long as a given condition remains true. Understanding how to use while loops effectively is a crucial skill for any Python developer.
while
LoopsIn programming, loops arecontrol flow statements that allow you to repeat a given set of operations a number of times. In practice, you’ll find two main types of loops:
for
loops are mostly used to iterate aknown number of times, which is common when you’re processing data collections with a specific number of data items.while
loops are commonly used to iterate anunknown number of times, which is useful when the number of iterations depends on a given condition.Python has both of these loops and in this tutorial, you’ll learn aboutwhile
loops. In Python, you’ll generally usewhile
loops when you need to repeat a series of tasks an unknown number of times.
Pythonwhile
loops arecompound statements with aheader and acode block that runs until a given condition becomes false. The basic syntax of awhile
loop is shown below:
whilecondition:<body>
In this syntax,condition
is anexpression that the loop evaluates for its truth value. If the condition is true, then the loop body runs. Otherwise, the loop terminates. Note that the loop body can consist of one or more statements that must be indented properly.
Here’s a more detailed breakdown of this syntax:
while
is the keyword that initiates the loop header.condition
is an expression evaluated for truthiness that defines the exit condition.<body>
consists of one or more statements to execute in each iteration.Here’s a quick example of how you can use awhile
loop to iterate over a decreasing sequence of numbers:
>>>number=5>>>whilenumber>0:...print(number)...number-=1...54321
In this example,number > 0
is the loop condition. If this condition returns a false value, the loop terminates. The body consists of a call toprint()
that displays the value on the screen. Next, you decrease the value ofnumber
. This change will produce a different result when the loop evaluates the condition in the next iteration.
The loop runs while the condition remains true. When the condition turns false, the loop terminates, and the program execution proceeds to the first statement after the loop body. In this example, the loop terminates whennumber
reaches a value less than or equal to0
.
If the loop condition doesn’t become false, then you have a potentially infinite loop. Consider the following loop, and keep your fingers near theCtrl+C key combination to terminate its execution:
>>>number=5>>>whilenumber!=0:...print(number)...number-=1...54321>>>number=5>>>whilenumber!=0:...print(number)...number-=2...531-1-3-5-7-9-11Traceback (most recent call last):...KeyboardInterrupt
In this example, the loop condition isnumber != 0
. This condition works when you decreasenumber
by1
. However, if you decrease it by 2, the condition may never become false, resulting in a potentially infinite loop. In such cases, you can usually terminate the loop by pressingCtrl+C, which raises aKeyboardInterrupt
exception on most operating systems.
Note that thewhile
loop checks its condition first before anything else happens. If it’s false to start with, then the loop body will never run:
>>>number=0>>>whilenumber>0:...print(number)...number-=1...
In this example, when the loop finds thatnumber
isn’t greater than0
, it immediately terminates the execution without entering the loop body. So, the body never executes.
Now that you know the basic syntax ofwhile
loops, it’s time to dive into some practical examples in Python. In the next section, you’ll see how these loops can be applied to real-world scenarios.
while
Loop SyntaxThe Pythonwhile
loop has some advanced features that make it flexible and powerful. These features can be helpful when you need to fine-tune the loop to meet specific execution flows.
So far, you’ve seen examples where the entire loop body runs on each iteration. Python provides twokeywords that let you modify that behavior:
break
: Immediately terminates a loop. The program execution then proceeds with the first statement following the loop body.continue
: Ends only the current iteration. The execution jumps back to the loop header, and the loop condition is evaluated to determine whether the loop will execute again.Python’swhile
loops also have additional syntax. They have anelse
clause that runs when the loop terminates naturally because the condition becomes true. In the following sections, you’ll learn more about how thebreak
andcontinue
statements work, as well as how to use theelse
clause effectively inwhile
loops.
break
Statement: Exiting a Loop EarlyWith thebreak
statement, you can terminate the execution of awhile
loop and make your program continue with the first statement immediately after the loop body.
Here’s a short script that demonstrates how thebreak
statement works:
break.py
number=6whilenumber>0:number-=1ifnumber==2:breakprint(number)print("Loop ended")
Whennumber
becomes2
, thebreak
statement is reached, and the loop terminates completely. The program execution jumps to the call toprint()
in the final line of the script.
Runningbreak.py
from the command line produces the following output:
$pythonbreak.py543Loop ended
The loop prints values normally. Whennumber
reaches the value of2
, thenbreak
runs, terminating the loop and printingLoop ended
to your screen. Note that2
and1
aren’t printed at all.
It’s important to note that it makes little sense to havebreak
statements outside ofconditionals. Suppose you include abreak
statement directly in the loop body without wrapping it in a conditional. In that case, the loop will terminate in the first iteration, potentially without running the entire loop body.
continue
Statement: Skipping Tasks in an IterationNext, you have thecontinue
statement. With this statement, you can skip some tasks in the current iteration when a given condition is met.
The next script is almost identical to the one in the previous section except for thecontinue
statement in place ofbreak
:
continue.py
number=6whilenumber>0:number-=1ifnumber==2:continueprint(number)print("Loop ended")
The output ofcontinue.py
looks like this:
$pythoncontinue.py54310Loop ended
This time, whennumber
is2
, thecontinue
statement terminates that iteration. That’s why2
isn’t printed. The control then returns to the loop header, where the condition is re-evaluated. The loop continues untilnumber
reaches0
, at which point it terminates as before.
else
Clause: Running Tasks at Natural Loop TerminationPython allows an optionalelse
clause at the end ofwhile
loops. The syntax is shown below:
whilecondition:<body>else:<body>
The code under theelse
clause will run only if thewhile
loop terminates naturally without encountering abreak
statement. In other words, it executes when the loop condition becomes false, and only then.
Note that it doesn’t make much sense to have anelse
clause in a loop that doesn’t have abreak
statement. In that case, placing theelse
block’s content after the loop—without indentation—will work the same and be cleaner.
When might anelse
clause on awhile
loop be useful? One common use case forelse
is when you need to break out of the loop. Consider the following example:
connection.py
importrandomimporttimeMAX_RETRIES=5attempts=0whileattempts<MAX_RETRIES:attempts+=1print(f"Attempt{attempts}: Connecting to the server...")# Simulating a connection scenariotime.sleep(0.3)ifrandom.choice([False,False,False,True]):print("Connection successful!")breakprint("Connection failed. Retrying...")else:print("All attempts failed. Unable to connect.")
This script simulates the process of connecting to an external server. The loop lets you try to connect a number of times, defined by theMAX_RETRIES
constant. If the connection is successful, then thebreak
statement terminates the loop.
Note: In the example above, you used therandom
module to simulate a successful or unsuccessful connection. You’ll use this module in a few other examples throughout this tutorial. To learn more about random data, check out theGenerating Random Data in Python (Guide) tutorial.
When all the connection attempts fail, theelse
clause executes, letting you know that the attempts were unsuccessful. Go ahead and run the script several times to check the results.
while
Loops in PythonWhen writingwhile
loops in Python, you should ensure that they’re efficient and readable. You also need to make sure that they terminate correctly.
Normally, you choose to use awhile
loop when you need to repeat a series of actions until a given condition becomes false or while it remains true. This type of loop isn’t the way to go when you need to process all the items in an iterable. In that case, you should use afor
loop instead.
In the following sections, you’ll learn how to usewhile
loops effectively, avoid infinite loops, implement control statements likebreak
andcontinue
, and leverage theelse
clause for handling loop completion gracefully.
while
LoopsA general use case for awhile
loop is waiting for a resource to become available before proceeding to use it. This is common in scenarios like the following:
Here’s a loop that continually checks if a given file has been created:
check_file.py
importtimefrompathlibimportPathfilename=Path("hello.txt")print(f"Waiting for{filename.name} to be created...")whilenotfilename.exists():print("File not found. Retrying in 1 second...")time.sleep(1)print(f"{filename} found! Proceeding with processing.")withopen(filename,mode="r")asfile:print("File contents:")print(file.read())
The loop in this script uses the.exists()
method on aPath
object. This method returnsTrue
if the target file exits. Thenot
operator negates the check result, returningTrue
if the file doesn’t exit. If that’s the case, then the loop waits for one second to run another iteration and check for the file again.
If you run this script, then you’ll get something like the following:
$pythoncheck_file.pyWaiting for hello.txt to be created...File not found. Retrying in 1 second...File not found. Retrying in 1 second...File not found. Retrying in 1 second......
In the meantime, you can open another terminal and create thehello.txt
file. When the loop finds the newly created file, it’ll terminate. Then, the code after the loop will run, printing the file content to your screen.
while
Loops for an Unknown Number of Iterationswhile
loops are also great when you need to process a stream of data with an unknown number of items. In this scenario, you don’t know the required number of iterations, so you can use awhile
loop withTrue
as its control condition. This technique provides a Pythonic way to write loops that will run an unknown number of iterations.
To illustrate, suppose you need to read a temperature sensor that continuously provides data. When the temperature is equal to or greater than 28 degrees Celsius, you should stop monitoring it. Here’s a loop to accomplish this task:
temperature.py
importrandomimporttimedefread_temperature():returnrandom.uniform(20.0,30.0)whileTrue:temperature=read_temperature()print(f"Temperature:{temperature:.2f}°C")iftemperature>=28:print("Required temperature reached! Stopping monitoring.")breaktime.sleep(1)
In this loop, you useTrue
as the loop condition, which generates a continually running loop. Then, you read the temperature sensor and print the current temperature value. If the temperature is equal to or greater than 25 degrees, you break out of the loop. Otherwise, you wait for a second and read the sensor again.
Modifying a collection during iteration can be risky, especially when you need to remove items from the target collection. In some cases, using awhile
loop can be a good solution.
For example, say that you need to process a list of values and remove each value after it’s processed. In this situation, you can use awhile
loop like the following:
>>>colors=["red","blue","yellow","green"]>>>whilecolors:...color=colors.pop(-1)...print(f"Processing color:{color}")...Processing color: greenProcessing color: yellowProcessing color: blueProcessing color: red
When you evaluate a list in aBoolean context, you getTrue
if it contains elements andFalse
if it’s empty. In this example,colors
remains true as long as it has elements. Once you remove all the items with the.pop()
method,colors
becomes false, and the loop terminates.
while
LoopGetting user input from the command line is a common use case forwhile
loops in Python. Consider the following loop that takes input using the built-ininput()
functions. The loop runs until you type the word"stop"
:
user_input.py
line=input("Type some text: ")whileline!="stop":print(line)line=input("Type some text: ")
Theinput()
function asks the user to enter some text. Then, you assign the result to theline
variable. The loop condition checks whether the content ofline
is different from"stop"
, in which case, the loop body executes. Inside the loop, you callinput()
again. The loop repeats until the user types the wordstop
.
This example works, but it has the drawback of unnecessarily repeating the call toinput()
. You can avoid the repetition using thewalrus operator as in the code snippet below:
>>>while(line:=input("Type some text: "))!="stop":...print(line)...Type some text: PythonPythonType some text: WalrusWalrusType some text: stop
In this updated loop, you get the user input in theline
variable using an assignment expression. At the same time, the expression returns the user input so that it can be compared to the sentinel value"stop"
.
while
LoopsUsing awhile
loop with the built-innext()
function may be a great way to fine-control the iteration process when working withiterators and iterables.
To give you an idea of how this works, you’ll rewrite afor
loop using awhile
loop instead. Consider the following code:
for_loop.py
requests=["first request","second request","third request"]print("\nWith a for loop")forrequestinrequests:print(f"Handling{request}")print("\nWith a while loop")it=iter(requests)whileTrue:try:request=next(it)exceptStopIteration:breakprint(f"Handling{request}")
The two loops are equivalent. When you run the script, each loop will handle the three requests in turn:
$pythonfor_loop.pyWith a for-loopHandling first requestHandling second requestHandling third requestWith a while-loopHandling first requestHandling second requestHandling third request
Python’sfor
loops are quite flexible and powerful, and you should generally preferfor
overwhile
if you need to iterate over a given collection. However, translating thefor
loop into awhile
loop, like above, gives you even more flexibility in how you handle the iterator.
Ado-while loop is a control flow statement that executes its code block at least once, regardless of whether the loop condition is true or false.
If you come from languages likeC,C++,Java, orJavaScript, then you may be wondering where Python’s do-while loop is. The bad news is that Python doesn’t have one. The good news is that you can emulate it using awhile
loop with abreak
statement.
Consider the following example, which takes user input in a loop:
>>>whileTrue:...number=int(input("Enter a positive number: "))...print(number)...ifnotnumber>0:...break...Enter a positive number: 11Enter a positive number: 44Enter a positive number: -1-1
Again, this loop takes the user input using the built-ininput()
function. The input is then converted into an integer number usingint()
. If the user enters a number that’s0
or lower, then thebreak
statement runs, and the loop terminates.
Note that to emulate a do-while loop in Python, the condition that terminates the loop goes at the end of the loop, and its body is abreak
statement. It’s also important to emphasize that in this type of loop, the body runs at least once.
while
Loops for Event LoopsAnother common and extended use case ofwhile
loops in Python is to createevent loops, which are infinite loops that wait for certain actions known asevents. Once an event happens, the loop dispatches it to the appropriateevent handler.
Some classic examples of fields where you’ll find event loops include the following:
For example, say that you want to implement a number-guessing game. You can do this with awhile
loop:
guess.py
fromrandomimportrandintLOW,HIGH=1,10secret_number=randint(LOW,HIGH)clue=""# Game loopwhileTrue:guess=input(f"Guess a number between{LOW} and{HIGH}{clue} ")number=int(guess)ifnumber>secret_number:clue=f"(less than{number})"elifnumber<secret_number:clue=f"(greater than{number})"else:breakprint(f"You guessed it! The secret number is{number}")
In this example, the game loop runs the game logic. First, it takes the user’s guess withinput()
, converts it into an integer number, and checks whether it’s greater or less than the secret number. Theelse
clause executes when the user’s guess is equal to the secret number. In that case, the loop breaks, and the game shows a winning message.
while
LoopsSometimes, you might write awhile
loop that doesn’t naturally terminate. A loop with this behavior is commonly known as aninfinite loop, although the name isn’t quite accurate because, in the end, you’ll have to terminate the loop somehow.
You may write an infinite loop eitherintentionally orunintentionally. Intentional infinite loops are powerful tools commonly used in programs that need to run continuously until an external condition is met, such as game loops, server processes, and event-driven apps like GUI apps or asynchronous code.
In contrast, unintentional infinitewhile
loops are often the result of some kind of logical issue that prevents the loop condition from ever becoming false. For example, this can happen when the loop:
In these cases, the loop erroneously continues to run until it’s terminated externally.
In the following sections, you’ll learn about both types of infinite loops and how to approach them in your code. To kick things off, you’ll start with unintentional infinite loops.
Suppose you write awhile
loop that never ends due to an internal error. Getting back to the example in the initial section of this tutorial, you have the following loop that runs continuously:
>>>number=5>>>whilenumber!=0:...print(number)...number-=2...531-1-3-5-7-9-11Traceback (most recent call last):...KeyboardInterrupt
To terminate this code, you have to pressCtrl+C, which interrupts the program’s execution from the keyboard. Otherwise, the loop would run indefinitely since its condition never turns false. In real-world code, you’d typically want to have a proper loop condition to prevent unintended infinite execution.
In most cases like this, you can prevent the potentially infinite loop by fixing the condition itself or the internal loop logic to make sure the condition becomes false at some point in the loop’s execution.
In the example above, you can modify the condition a bit to fix the issue:
>>>number=5>>>whilenumber>0:...print(number)...number-=2......531
This time, the loop doesn’t go down the0
value. Instead, it terminates whennumber
has a value that’s equal to or less than0
.
Alternatively, you can use additional conditionals in the loop body to terminate the loop usingbreak
:
>>>number=5>>>whilenumber!=0:...ifnumber<=0:...break...print(number)...number-=2...531
This loop has the same original loop condition. However, it includes a failsafe condition in the loop body to terminate it in case the main condition fails.
Figuring out how to fix an unintentional infinite loop will largely depend on the logic you’re using in the loop condition and body. So, you should analyze each case carefully to determine the correct solution.
Intentionally infinitewhile
loops are pretty common and useful. However, writing them correctly requires ensuring proper exit conditions, avoiding performance issues, and preventing unintended infinite execution.
For example, you might want to write code for a service that starts up and runs forever, accepting service requests.Forever, in this context, means until you shut it down.
The typical way to write an infinite loop is to use thewhile True
construct. To ensure that the loop terminates naturally, you should add one or morebreak
statements wrapped in proper conditions:
whileTrue:ifcondition_1:break...ifcondition_2:break...ifcondition_n:break
This syntax works well when you have multiple reasons to end the loop. It’s often cleaner to break out from several different locations rather than try to specify all the termination conditions in the loop header.
To see this construct in practice, consider the following infinite loop that asks the user to provide their password:
password.py
MAX_ATTEMPTS=3correct_password="secret123"attempts=0whileTrue:password=input("Password: ").strip()attempts+=1ifpassword==correct_password:print("Login successful! Welcome!")breakifattempts>=MAX_ATTEMPTS:print("Too many failed attempts.")breakelse:print(f"Incorrect password.{MAX_ATTEMPTS-attempts} attempts left.")
This loop has two exit conditions. The first condition checks whether the password is correct. The second condition checks whether the user has reached the maximum number of attempts to provide a correct password. Both conditions include abreak
statement to finish the loop gracefully.
You’ve learned a lot about Python’swhile
loop, which is a crucial control flow structure for iteration. You’ve learned how to usewhile
loops to repeat tasks until a condition is met, how to tweak loops withbreak
andcontinue
statements, and how to prevent or write infinite loops.
Understandingwhile
loops is essential for Python developers, as they let you handle tasks that require repeated execution based on conditions.
In this tutorial, you’ve learned how to:
while
loopswhile
loopswhile
loops for tasks withan unknown number of iterationsbreak
andcontinue
statementsThis knowledge enables you to write dynamic and flexible code, particularly in situations where the number of iterations is unknown beforehand or depends on one or more conditions.
Get Your Code:Click here to download the free sample code that shows you how to work with while loops in Python.
Now that you have some experience with Pythonwhile
loops, you can use the questions and answers below to check your understanding and recap what you’ve learned.
These FAQs are related to the most important concepts you’ve covered in this tutorial. Click theShow/Hide toggle beside each question to reveal the answer.
In Python, awhile
loop is a control flow statement that lets you repeatedly execute a block of code as long as a specified condition remains true.
You use awhile
loop when the number of iterations is uncertain, and afor
loop when iterating a known number of times over a sequence.
You prevent an infinite loop by ensuring that the loop’s condition will eventually become false through proper logic in the loop condition and body.
You use thebreak
statement to immediately exit awhile
loop, regardless of the loop’s condition.
Yes, you can use anelse
clause with awhile
loop to execute code when the loop terminates naturally without abreak
statement.
Take the Quiz: Test your knowledge with our interactive “Python while Loops: Repeating Tasks Conditionally” quiz. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
Python while Loops: Repeating Tasks ConditionallyIn this quiz, you'll test your understanding of Python's while loop. This loop allows you to execute a block of code repeatedly as long as a given condition remains true. Understanding how to use while loops effectively is a crucial skill for any Python developer.
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding:Mastering While Loops
🐍 Python Tricks 💌
Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.
AboutLeodanis Pozo Ramos
Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.
» More about LeodanisMasterReal-World Python Skills With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
MasterReal-World Python Skills
With Unlimited Access to Real Python
Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:
What Do You Think?
What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students.Get tips for asking good questions andget answers to common questions in our support portal.
Keep Learning
Already have an account?Sign-In
Almost there! Complete this form and click the button below to gain instant access:
Python while Loops: Repeating Tasks Conditionally (Sample Code)