How Can You Emulate Do-While Loops in Python?

How Can You Emulate Do-While Loops in Python?

by Leodanis Pozo Ramos Reading time estimate 14m 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:

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

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

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

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

Language: JavaScript
 1// guess.js
 2
 3const LOW = 1;
 4const HIGH = 10;
 5
 6let secretNumber = Math.floor(Math.random() * HIGH) + LOW;
 7let clue =