How Can You Emulate Do-While Loops in Python?

How Can You Emulate Do-While Loops in Python?

by Leodanis Pozo Ramos basics best-practices python

If you came to Python from a language like C, C++, Java, or JavaScript, then you may be missing their do-while loop construct. A do-while loop is a common control flow statement that executes its code block at least once, regardless of whether the loop 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:

C
#include <stdio.h>

int main() {
    int number;
    do {
        printf("Enter a positive number: ");
        scanf("%d", &number);
        printf("%d\n", number);
    } while (number > 0);
    return 0;
}

This small program runs a dowhile loop that asks the user to enter a positive number. The input is then stored in number 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:

Shell
Enter a positive number: 1
1
Enter a positive number: 4
4
Enter a positive number: -1
-1

The loop condition, number > 0, is evaluated at the end of the loop, which guarantees that the loop’s body will run at least once. This characteristic distinguishes do-while loops from regular while 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.

One reason for having a do-while loop construct is efficiency. For example, if the loop condition implies costly operations and the loop must run n times (n ≥ 1), then the condition will run n times in a do-while loop. In contrast, a regular while loop will run the costly condition n + 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 why Guido van Rossum rejected PEP 315, 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 to revive 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 with while that behave like do-while loops.

In Short: Use a while Loop and the break Statement

The most common technique to emulate a do-while loop in Python is to use an infinite while loop with a break statement wrapped in an if statement that checks a given condition and breaks the iteration if that condition becomes true:

Python
while True:
    # Do some processing...
    # Update the condition...
    if condition:
        break

This loop uses True 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 the break statement breaks out of the loop, and the program execution continues its normal path.

Here’s how to write the Python equivalent to the C program that you wrote in the introduction to this tutorial:

Python
>>> while True:
...     number = int(input("Enter a positive number: "))
...     print(number)
...     if not number > 0:
...         break
...
Enter a positive number: 1
1
Enter a positive number: 4
4
Enter a positive number: -1
-1

This loop takes the user’s input using the built-in input() function. The input is then converted into an integer number using int(). If the user enters a number that’s 0 or lower, then the break 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 use while and break 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 is accepting and processing the user’s input. As a practical example, say that you have a number-guessing game implemented in JavaScript. The code uses a dowhile loop to process the user’s input:

JavaScript
 1// guess.js
 2
 3const LOW = 1;
 4const HIGH = 10;
 5
 6let secretNumber = Math.floor(Math.random() * HIGH) + LOW;
 7let clue = '';
 8let number = null;
 9
10do {
11  let guess = prompt(`Guess a number between ${LOW} and ${HIGH} ${clue}`);
12  number = parseInt(guess);
13  if (number > secretNumber) {
14    clue = `(less than ${number})`;
15  } else if (number < secretNumber) {
16    clue = `(greater than ${number})`;
17  }
18} while (number != secretNumber);
19
20alert(`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 define variables 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 dowhile loop 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 clue is set to an appropriate message.

  • Line 15 checks if the input number is less than the secret number and then sets clue accordingly.

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

Python
# guess.py

from random import randint

LOW, HIGH = 1, 10

secret_number = randint(LOW, HIGH)
clue = ""

while True:
    guess = input(f"Guess a number between {LOW} and {HIGH} {clue} ")
    number = int(guess)
    if number > secret_number:
        clue = f"(less than {number})"
    elif number < secret_number:
        clue = f"(greater than {number})"
    else:
        break

print(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 regular while loop because Python doesn’t have dowhile loops. In this Python implementation, when the user guesses the secret number, the else clause runs, breaking the loop. The final line of code prints the successful guess message.

Using an infinite loop and a break 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 condition n + 1 times for n iterations Checks the loop condition n times, with n 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 infinite while loop and the break 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 operation before 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 a while 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:

Python
condition = do_something()

while condition:
    condition = do_something()

The first call to do_something() guarantees that the required functionality runs at least once. The call to do_something() inside the loop runs only when condition 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:

Python
# guess.py

from random import randint

LOW, HIGH = 1, 10

secret_number = randint(LOW, HIGH)
clue = ""

def process_move(clue):
    user_input = input(f"Guess a number between {LOW} and {HIGH} {clue} ")
    number = int(user_input)
    if number > secret_number:
        clue = f"(less than {number})"
    elif number < secret_number:
        clue = f"(greater than {number})"
    return number, clue

number, clue = process_move(clue)  # First iteration

while number != 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 into process_move(). This function returns the current number, which you’ll use later when checking the loop condition. It also returns the clue message.

Note that process_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 to True is another option to emulate a do-while loop. In this case, you just need to set the loop condition to True right before the loop starts to run. This practice ensures that the loop’s body will run at least once:

Python
do = True

while do:
    do_something()
    if condition:
        do = False

This alternative construct is pretty similar to the one that you used in the previous section. The main difference is that the loop condition is a Boolean variable that gets updated inside the loop.

This technique is also similar to the one that uses an infinite while loop and a break statement. However, this one is more explicit and readable because it lets you use descriptive variable names instead of a bare break statement and a hard-coded condition like True.

You can use this technique to rewrite your number-guessing game like in the following code example:

Python
# guess.py

from random import randint

LOW, HIGH = 1, 10

secret_number = randint(LOW, HIGH)
clue = ""
number_guessed = False

while not number_guessed:
    user_input = input(f"Guess a number between {LOW} and {HIGH} {clue} ")
    number = int(user_input)
    if number > secret_number:
        clue = f"(less than {number})"
    elif number < secret_number:
        clue = f"(greater than {number})"
    else:
        number_guessed = True

print(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, then number_guessed is set to True, and the program jumps out of the loop execution.

Conclusion

In this tutorial, you’ve learned to emulate 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 an infinite while loop with a conditional statement at the end of the loop’s body. This conditional controls the loop and jumps out of it using the break 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 to True to control the loop.

With all this knowledge, you’re ready to start emulating do-while loops in your own Python code.

🐍 Python Tricks 💌

Get a short & sweet Python 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

About Leodanis 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:

Master Real-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 »

Master Real-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 and get answers to common questions in our support portal.


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

Keep Learning

Related Topics: basics best-practices python