Movatterモバイル変換


[0]ホーム

URL:


— FREE Email Series —

🐍 Python Tricks 💌

Python Tricks Dictionary Merge

🔒 No spam. Unsubscribe any time.

Browse TopicsGuided Learning Paths
Basics Intermediate Advanced
apibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnumpyprojectspythontestingtoolsweb-devweb-scraping

Table of Contents

Recommended Video Course
Mastering While Loops

Python while Loops: Repeating Tasks Conditionally

Python while Loops: Repeating Tasks Conditionally

byLeodanis Pozo Ramos Mar 03, 2025basicspython

Table of Contents

Remove ads

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.
  • Awhile 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.
  • Python lacks a built-in do-while loop, but you can emulate it using awhile 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:


Python while Loops: Repeating Tasks Conditionally

Interactive Quiz

Python while Loops: Repeating Tasks Conditionally

In 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.

Getting Started With Pythonwhile Loops

In 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:

  1. 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.
  2. 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:

Python Syntax
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:

Python
>>>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:

Python
>>>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:

Python
>>>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.

Using Advancedwhile Loop Syntax

The 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.

Thebreak Statement: Exiting a Loop Early

With 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:

Pythonbreak.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:

Shell
$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.

Thecontinue Statement: Skipping Tasks in an Iteration

Next, 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:

Pythoncontinue.py
number=6whilenumber>0:number-=1ifnumber==2:continueprint(number)print("Loop ended")

The output ofcontinue.py looks like this:

Shell
$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.

Theelse Clause: Running Tasks at Natural Loop Termination

Python allows an optionalelse clause at the end ofwhile loops. The syntax is shown below:

Python Syntax
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:

Pythonconnection.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_RETRIESconstant. 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.

Writing Effectivewhile Loops in Python

When 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.

Running Tasks Based on a Condition Withwhile Loops

A 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:

Pythoncheck_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:

Shell
$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.

Usingwhile Loops for an Unknown Number of Iterations

while 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:

Pythontemperature.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.

Removing Items From an Iterable in a Loop

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:

Python
>>>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.

Getting User Input With awhile Loop

Getting 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":

Pythonuser_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 thelinevariable. 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:

Python
>>>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".

Traversing Iterators Withwhile Loops

Using 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:

Pythonfor_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:

Shell
$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.

Emulating Do-While Loops

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:

Python
>>>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.

Usingwhile Loops for Event Loops

Another 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:

Pythonguess.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.

Exploring Infinitewhile Loops

Sometimes, 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:

  • Fails to update a condition variable
  • Uses a condition that’s logically flawed

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.

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:

Python
>>>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:

Python
>>>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:

Python
>>>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.

Intentional Infinite Loops

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:

Python Syntax
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:

Pythonpassword.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.

Conclusion

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:

  • Understand thesyntax of Pythonwhile loops
  • Repeat tasks when acondition is true withwhile loops
  • Usewhile loops for tasks withan unknown number of iterations
  • Control loop execution withbreak andcontinue statements
  • Avoid unintended infinite loops andwrite correct ones

This 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.

Frequently Asked Questions

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:


Python while Loops: Repeating Tasks Conditionally

Interactive Quiz

Python while Loops: Repeating Tasks Conditionally

In 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.

Python Tricks Dictionary Merge

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 Leodanis

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

MasterReal-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

MasterReal-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

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.


Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics:basicspython

Recommended Video Course:Mastering While Loops

Related Tutorials:

Keep reading Real Python by creating a free account or signing in:

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

Python while Loops: Repeating Tasks Conditionally (Sample Code)

🔒 No spam. We take your privacy seriously.


[8]ページ先頭

©2009-2025 Movatter.jp