Basics Intermediate Advanced
aialgorithmsapibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnewsnumpyprojectspythonstdlibtestingtoolsweb-devweb-scraping

How Can You Emulate Do-While Loops in Python?
Table of Contents
If you came to Python from a language likeC,C++,Java, orJavaScript, then you may be missing theirdo-while loop construct. A do-while loop is a commoncontrol flow statement that executes its code block at least once, regardless of whether theloop condition is true or false. This behavior relies on the fact that the loop condition is evaluated at the end of each iteration. So, the first iteration always runs.
One of the most common use cases for this type of loop is accepting and processing the user’s input. Consider the following example written in C:
#include<stdio.h>intmain(){intnumber;do{printf("Enter a positive number: ");scanf("%d",&number);printf("%d\n",number);}while(number>0);return0;}This small program runs ado …while loop that asks the user to enter a positive number. The input is then stored innumber and printed to the screen. The loop keeps running these operations until the user enters a non-positive number.
If you compile and run this program, then you’ll get the following behavior:
Enter a positive number: 11Enter a positive number: 44Enter a positive number: -1-1The loop condition,number > 0, is evaluated at the end of the loop, which guarantees that the loop’sbody will run at least once. This characteristic distinguishes do-while loops from regularwhile loops, which evaluate the loop condition at the beginning. In a while loop, there’s no guarantee of running the loop’s body. If the loop condition is false from the start, then the body won’t run at all.
Note: In this tutorial, you’ll refer to the condition that controls a while or do-while loop as theloop condition. This concept shouldn’t be confused with theloop’s body, which is the code block that’s sandwiched between curly brackets in languages like C or indented in Python.
One reason for having a do-while loop construct isefficiency. For example, if the loop condition implies costly operations and the loop must runn times (n ≥ 1), then the condition will runn times in a do-while loop. In contrast, a regular while loop will run the costly conditionn + 1 times.
Python doesn’t have a do-while loop construct. Why? Apparently, the core developers never found a good syntax for this type of loop. Probably, that’s the reason whyGuido van Rossumrejected PEP315, which was an attempt to add do-while loops to the language. Some core developers would prefer to have a do-while loop and are looking torevive the discussion around this topic.
In the meantime, you’ll explore the alternatives available in Python. In short,how can you emulate do-while loops in Python? In this tutorial, you’ll learn how you can create loops withwhile that behave like do-while loops.
Free Download:Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.
In Short: Use awhile Loop and thebreak Statement
The most common technique to emulate a do-while loop in Python is to use an infinitewhile loop with abreak statement wrapped in anif statement that checks a given condition and breaks the iteration if that condition becomes true:
whileTrue:# Do some processing...# Update the condition...ifcondition:breakThis loop usesTrue as its formal condition. This trick turns the loop into an infinite loop. Before the conditional statement, the loop runs all the required processing and updates the breaking condition. If this condition evaluates to true, then thebreak statement breaks out of the loop, and the program execution continues its normal path.
Note: Using an infinite loop and abreak statement allows you to emulate do-while loops. This technique is what the Python community generallyrecommends, but it’s not entirely safe.
For example, if you introduce acontinue statement before thebreak statement, then the loop can miss the breaking condition and run into an uncontrolled infinite loop.
Here’s how to write the Python equivalent to the C program that you wrote in the introduction to this tutorial:
>>>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-1This loop takes the user’s 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.
At times, you’ll encounter situations where you need a guarantee that a loop runs at least once. In those cases, you can usewhile andbreak as above. In the following section, you’ll code a number-guessing game that uses such a do-while loop to accept and process the user’s input at the command line.
How Do Do-While Loops Work in Practice?
The most common use case of do-while loops isaccepting and processing the user’s input. As a practical example, say that you have a number-guessing game implemented inJavaScript. The code uses ado …while loop to process the user’s input:
1// guess.js 2 3constLOW=1; 4constHIGH=10; 5 6letsecretNumber=Math.floor(Math.random()*HIGH)+LOW; 7letclue=''; 8letnumber=null; 910do{11letguess=prompt(`Guess a number between${LOW} and${HIGH}${clue}`);12number=parseInt(guess);13if(number>secretNumber){14clue=`(less than${number})`;15}elseif(number<secretNumber){16clue=`(greater than${number})`;17}18}while(number!=secretNumber);1920alert(`You guessed it! The secret number is${number}`);This script does several things. Here’s a breakdown of what’s happening:
Lines 3 and 4 define two constants to delimit the interval in which the secret number will live.
Lines 6 to 8 definevariables to store the secret number, a clue message, and an initial value for
number, which will hold the user’s input.Line 10 starts a
do…whileloop to process the user’s input and determine if the user has guessed the secret number.Line 11 defines a local variable,
guess, to store the user’s input as provided at the command line.Line 12 converts the input value into an integer using
parseInt().Line 13 defines a conditional statement that checks if the input number is greater than the secret number. If that’s the case, then
clueis set to an appropriate message.Line 15 checks if the input number is less than the secret number and then sets
clueaccordingly.Line 18 defines the loop condition to check if the input number is different from the secret number. In this specific example, the loop will continue running until the user guesses the secret number.
Line 20 finally launches an alert box to inform the user of a successful guess.
Now say that you want to translate the above example into Python code. An equivalent number-guessing game in Python would look something like this:
# guess.pyfromrandomimportrandintLOW,HIGH=1,10secret_number=randint(LOW,HIGH)clue=""whileTrue: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}")This Python code works just like its equivalent JavaScript code. The main difference is that in this case, you’re using a regularwhile loop because Python doesn’t havedo …while loops. In this Python implementation, when the user guesses the secret number, theelse clause runs, breaking the loop. The final line of codeprints the successful guess message.
Using an infinite loop and abreak statement like you did in the example above is the most widely used approach for emulating a do-while loop in Python.
What Are the Differences Between Do-While and While Loops?
In short, the main difference between do-while loops and while loops is that the former executes its body at least once because the loop condition is checked at the end. On the other hand, the body of a regular while loop executes if the condition evaluates to true, which is tested at the beginning of the loop.
Here’s a table that summarizes the key differences between the two types of loops:
| while | do-while |
|---|---|
| Is an entry-controlled loop | Is an exit-controlled loop |
| Runs only while the loop condition is true | Runs until the loop condition becomes false |
| Checks the condition first and then executes the loop’s body | Executes the loop’s body and then checks the condition |
| Executes the loop’s body zero times if the loop condition is initially false | Executes the loop’s body at least once, regardless of the truth value of the loop condition |
| Checks the loop conditionn + 1 times forn iterations | Checks the loop conditionn times, withn being the number of iterations |
The while loop is a control flow structure that provides a general-purpose and versatile loop. It allows you to repeatedly run a set of statements while a given condition remains true. Use cases for the do-while loop are more specific. It’s mostly used in cases where checking the loop condition only makes sense if the loop’s body has already run at least once.
What Alternative Can You Use to Emulate Do-While Loops in Python?
At this point, you’ve already learned the recommended or most common way to emulate a do-while loop in Python. However, Python is pretty flexible when it comes to emulating this type of loop. Some programmers always go with the infinitewhile loop and thebreak statement. Other programmers use their own formula.
In this section, you’ll go through some alternative techniques for emulating a do-while loop. The first alternative runs your first operationbefore the loop starts. The second alternative implies using a loop condition that’s initially set to a true value before the loop begins.
Doing the First Operation Before the Loop
As you already learned, the most relevant feature of do-while loops is that the loop’s body always runs at least once. To emulate this functionality using awhile loop, you can take the loop’s body and run it before the loop starts. Then you can repeat the body inside the loop.
This solution sounds repetitive, and it would be if you didn’t use some kind of trick. Fortunately, you can use a function to pack the loop’s body and prevent repetition. With this technique, your code will look something like this:
condition=do_something()whilecondition:condition=do_something()The first call todo_something() guarantees that the required functionality runs at least once. The call todo_something() inside the loop runs only whencondition is true. Note that you need to update the loop condition in every iteration for this pattern to work correctly.
The code below shows how you’d implement your number-guessing game using this technique:
# guess.pyfromrandomimportrandintLOW,HIGH=1,10secret_number=randint(LOW,HIGH)clue=""defprocess_move(clue):user_input=input(f"Guess a number between{LOW} and{HIGH}{clue} ")number=int(user_input)ifnumber>secret_number:clue=f"(less than{number})"elifnumber<secret_number:clue=f"(greater than{number})"returnnumber,cluenumber,clue=process_move(clue)# First iterationwhilenumber!=secret_number:number,clue=process_move(clue)print(f"You guessed it! The secret number is{number}")In this new version of your number-guessing game, you pack all the loop’s functionality intoprocess_move(). This function returns the current number, which you’ll use later when checking the loop condition. It also returns the clue message.
Note thatprocess_move() runs once before the loop starts, mimicking the do-while loop’s main feature of running its body at least once.
Inside the loop, you call the function to run the game’s primary functionality and update the loop condition accordingly.
Using an Initially True Loop Condition
Using a loop condition initially set toTrue is another option to emulate a do-while loop. In this case, you just need to set the loop condition toTrue right before the loop starts to run. This practice ensures that the loop’s body will run at least once:
do=Truewhiledo:do_something()ifcondition:do=FalseThis alternative construct is pretty similar to the one that you used in the previous section. The main difference is that the loop condition is aBoolean variable that gets updated inside the loop.
This technique is also similar to the one that uses an infinitewhile loop and abreak statement. However, this one is more explicit and readable because it lets you use descriptive variable names instead of a barebreak statement and a hard-coded condition likeTrue.
Note: Sometimes it’s more natural to name the Boolean variable so that you set it toTrue in order to break out of the loop. In those cases, you can start the loop with something likewhile not done: and setdone toTrue inside the loop.
You can use this technique to rewrite your number-guessing game like in the following code example:
# guess.pyfromrandomimportrandintLOW,HIGH=1,10secret_number=randint(LOW,HIGH)clue=""number_guessed=Falsewhilenotnumber_guessed:user_input=input(f"Guess a number between{LOW} and{HIGH}{clue} ")number=int(user_input)ifnumber>secret_number:clue=f"(less than{number})"elifnumber<secret_number:clue=f"(greater than{number})"else:number_guessed=Trueprint(f"You guessed it! The secret number is{number}")In this example, you first define a Boolean variable,number_guessed, which allows you to control the loop. Inside the loop, you process the user’s input as usual. If the user guesses the secret number, thennumber_guessed is set toTrue, and the program jumps out of the loop execution.
Conclusion
In this tutorial, you’ve learned toemulate a do-while loop in Python. The language doesn’t have this loop construct, which you can find in languages like C, C++, Java, and JavaScript. You learned that you can always write a do-while loop with the help of a regular while loop, and you can use one of several different patterns to accomplish it.
The most common technique to emulate do-while loops is to create aninfinitewhile loop with a conditional statement at the end of the loop’s body. This conditional controls the loop and jumps out of it using thebreak statement.
You also learned how to use a couple of alternative techniques to provide the same functionality as a do-while loop. Your options include doing the first set of operations before the loop or using a Boolean variable initially set toTrue to control the loop.
With all this knowledge, you’re ready to start emulating do-while loops in your own Python code.
Free Download:Get a sample chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.
🐍 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 a self-taught Python developer, educator, and technical writer with over 10 years of experience.
» 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.
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
Keep reading Real Python by creating a free account or signing in:
Already have an account?Sign-In





