In this tutorial, you’ll learn how to emulate a do-while loop in Python.

In any programming language, loops help you perform certain actions repeatedly, depending on a looping condition. Python supports the while and for loop constructs but does not natively support the do-while loop.

However, you can emulate a do-while loop by understanding how it works— using existing loops and loop control statements in Python.

You’ll learn how to do this over the next few minutes. Let’s begin!

What is the Do-While Loop Construct?

What is the Do-While Loop Construct

If you have programmed in languages such as C or C++, you’d have probably come across the do-while loop construct.

In a do-while loop, the set of statements in the loop body—within the block delimited by curly braces—are executed first and then the looping condition is checked.

You can run the following C examples in Geekflare’s online C compiler—right from your browser.

Consider the following code snippet:

//do_while_example1

#include <stdio.h>

int main() {
    int count = 1;
    printf("Do-While loop: \n");
    
    do{
        printf("Loop runs...");
        }while(count<0);

    return 0;
}

Here’s the output.

Output

Do-While loop: 
Loop runs...

In the above example:

  • The value of count is 1, and the looping condition is count < 0. However, the loop runs once even though the looping condition is initially False.
  • This is in contrast to a while loop that only executes if the looping condition is True in the first place.
//while_example1

#include <stdio.h>

int main() {
    int count = 1;
    printf("While loop: \n");
    
    while(count<0){
        printf("Loop runs...");
        }

    return 0;
}

As mentioned, the looping condition, count < 0 is False initially the count variable is initialized to 1. So upon compiling and running the above code, we see that the statement in the while loop body is not executed.

Output

While loop: 
//loop body does not run!

While vs. Do-While: An Overview of the Differences

Let’s take a closer look at the differences between while and do-while loops.

While vs Do-While: An Overview of the Differences

Consider this example:

//do_while_example2

#include <stdio.h>

int main() {
    int count = 1;
    printf("Do-while loop: \n");
    
    do{
       printf("%d\n",count);
       count++;
    }while(count<5);

    return 0;
}

In the above code cell:

  • The count variable is initialized to 1.
  • We use a do-while loop.
  • The count variable is incremented by 1 during each pass through the loop, and the looping condition is set to count < 5.

Here’s a visual explanation of how the execution occurs: how the do-while loop works and checks for the looping condition four times.

do-while-loop-example
Output

Do-while loop: 
1
2
3
4

If you use a while loop instead, this is what we’d have.

//while_example2

#include <stdio.h>

int main() {
    int count = 1;
    printf("While loop: \n");
    
    while(count<5){
       printf("%d\n",count);
       count++;
    };

    return 0;
}

The figure below explains the while loop’s execution; in this example, the while loop checks the looping condition five times.

while-loop-example
Output

While loop: 
1
2
3
4

Although the outputs for the above while and do-while loops are identical, there are some subtle differences.

In a while loop, the check for condition comes first, followed by the loop body. So if you want the loop to run K times, there should be exactly K runs where the looping condition is True. In iteration number K+1, the condition becomes False, and the control breaks out of the loop.

On the other hand, if you use a do-while loop: the looping condition is checked for the K-th time only after K passes through the loop.

So why is this marginal improvement helpful?🤔

Suppose the looping condition is computationally expensive: for example, involves a call to a recursive function, a complex mathematical operation, and so on.

In such cases, for K repetitions of the loop body, it would be beneficial to use a do-while loop instead.

While vs. Do-While Summary

Let’s tabulate the key differences we’ve learned. 👩‍🏫

While LoopDo-While Loop
Check for looping condition: Before the execution of the loop bodyCheck for looping condition: After the execution of the loop body
If the condition is False initially, the loop body is not executed.If the condition is False initially, the loop body is executed exactly once.
The looping condition is checked K times for K passes through the loop.The looping condition is checked K-1 times for K passes through the loop.
When to use while loop?
– Loop should run so long as the condition is True
– For entry-controlled loops
– When the looping condition is not computationally expensive
When to use a do-while loop?
– Loop should run at least once for an initially False looping condition
– For exit-controlled loops
– When the looping condition is computationally expensive

Emulating Do-While Loop Behavior in Python

From the previous section, we have the following two conditions to emulate the do-while loop:

  • The statements in the loop body should execute at least once—regardless of whether the looping condition is True or False
  • The condition should be checked after executing statements in the loop body. If the condition is False, the control should break out of the loop: exit control.

Infinite While Loop and Break Statement in Python

do-while-python

You can define an infinite while loop in Python, as shown below.

while True:
    pass

# Instead of True, you can have any condition that is always True

while always-True-condition:
   pass

The break statement can be used to break out of a loop body and transfer control to the first statement outside the loop body.

while <condition>:
    if <some-condition>:
        break

In the very first do-while loop example in C, the condition to continue looping is count < 0. So the condition to break out of the loop is a count value of zero or greater than zero, (count >= 0).

Here’s the emulation of the do-while loop in Python:

count = 1
while True:
    print("Loop runs...")
    if(count >= 0):
        break

Python Do-While Loop Examples

We’ll revisit the examples from the previous section and rewrite them in Python by emulating do while loop.

#1. Let’s revisit the example: printing out values of the count variable when count is less than five.

We know how to define an infinite loop so that the loop body executes at least once.

The looping should continue so long as the count is less than five. Therefore, when the count reaches five, we should break out of the loop. So count == 5 is the exit control condition.

Putting it together, we have:

count = 1
while True:
  print(f"Count is {count}")
  count += 1
  if count==5:
    break
Output

Count is 1
Count is 2
Count is 3
Count is 4

#2. We can also rewrite the number guessing game as a Python do-while construct.

In the number guessing game, we validate a user’s guesses against a predefined secret number. The user should guess the secret number within a certain number of maximum attempts allowed, say, max_guesses.

The code should prompt the user for input, regardless of whether their guess is right or wrong. We can do this using an infinite while loop.

So when should we break out of the loop?

The control should break out of the loop when any one of the following occurs:

  1. When the user has guessed the number
  2. When the user hasn’t guessed the number yet, but has exhausted the number of guesses available. The number of incorrect guesses by the user = max_guesses.

The code cell below shows how we can do it.

import random

low, high = 5,50

secret_number = random.choice(range(low,high))

max_guesses = 10

num_guesses = 0

while True:
    guess = int(input("\nGuess a number:"))
    num_guesses += 1
    
    conditions = [num_guesses==max_guesses,guess==secret_number]
    
    if any(conditions):
        break

Instead of breaking out of the loop, we can add explanatory print() statements when we encounter each of the above conditions and then break out of the loop.

import random

low, high = 5,50

secret_number = random.choice(range(low,high))

print(secret_number)

max_guesses = 10

num_guesses = 0

while True:
    guess = int(input("\nGuess a number:"))
    num_guesses += 1
    
    if guess==secret_number:
        print("Congrats, you guessed it right!")
        break
    if num_guesses==max_guesses:
        print("Sorry, you have no more guesses left!")
        break

Two sample outputs are shown below.

In this sample output, the break statement breaks out of the loop when the user guesses the secret number correctly.

# Sample output when secret_number = 43 and user gets it right!

Guess a number:4

Guess a number:3

Guess a number:43
Congrats, you guessed it right!

Here’s another sample output when the user reaches the maximum number of guesses available but fails to guess the secret number correctly.

# Sample output when secret_number = 33 and user fails to guess it right!

Guess a number:3

Guess a number:15

Guess a number:21

Guess a number:50

Guess a number:17

Guess a number:6

Guess a number:18

Guess a number:5

Guess a number:12

Guess a number:43
Sorry, you have no more guesses left!

Conclusion

I hope this tutorial helped you understand how to emulate a do-while loop in Python.

Here are the key takeaways:

  • Use an infinite loop to ensure the loop body runs at least once. It could be a trivial infinite loop such as while True, or it could be while <condition>, such that the condition is always True.
  • Check for the exit condition inside the loop and use the break statement to break out of the loop under a specific condition.

Next, learn how to use for loops and the enumerate() function in Python.