How to Emulate a Do-While Loop in Python
Unlike many programming languages (C, C++, Java, JavaScript), Python doesn't have a built-in do-while loop. A do-while loop executes its body at least once before checking the condition, which is useful when you need to process something before deciding whether to continue.
In this guide, you'll learn multiple ways to emulate do-while loop behavior in Python, with practical examples that demonstrate when each approach is most appropriate.
What Is a Do-While Loop?
In languages that support it, a do-while loop looks like this (pseudocode):
do {
// execute this code
} while (condition);
The key difference from a regular while loop:
whileloop: Checks the condition before each iteration. The body may never execute.do-whileloop: Checks the condition after each iteration. The body always executes at least once.
Using while True with break (Recommended)
The most common and Pythonic way to emulate a do-while loop is to use an infinite while True loop with a conditional break at the end:
while True:
# Code that always executes at least once
user_input = input("Enter a number (0 to quit): ")
number = int(user_input)
print(f"You entered: {number}")
# Check condition at the end (like do-while)
if number == 0:
break
print("Loop has exited.")
Output:
Enter a number (0 to quit): 5
You entered: 5
Enter a number (0 to quit): 3
You entered: 3
Enter a number (0 to quit): 0
You entered: 0
Loop has exited.
The body executes at least once. The user is always prompted at least one time before the condition is checked.
This is the most widely recommended approach in Python. It's clean, explicit, and immediately recognizable as a do-while pattern to experienced Python developers.
Practical Example: Input Validation
A classic do-while use case is validating user input. You need to ask at least once:
while True:
password = input("Create a password (min 8 characters): ")
if len(password) >= 8:
print("Password accepted!")
break
else:
print(f"Too short ({len(password)} chars). Try again.\n")
Output:
Create a password (min 8 characters): hi
Too short (2 chars). Try again.
Create a password (min 8 characters): hello123
Password accepted!
Using a Flag Variable
A flag variable controls whether the loop should continue. The flag starts as True and is set to False when the exit condition is met:
keep_going = True
while keep_going:
user_input = input("Enter 'quit' to exit: ")
print(f"You typed: {user_input}")
if user_input.lower() == 'quit':
keep_going = False
print("Loop has exited.")
Output:
Enter 'quit' to exit: hello
You typed: hello
Enter 'quit' to exit: world
You typed: world
Enter 'quit' to exit: quit
You typed: quit
Loop has exited.
This approach is useful when the exit logic is complex or when you need to reference the flag from multiple places within the loop body.
Using a Condition Variable
Initialize a condition variable so the loop always enters on the first iteration, then update it based on the result:
import random
result = None # Ensures the loop runs at least once
while result != 6:
result = random.randint(1, 6)
print(f"Rolled: {result}")
print(f"Got a 6! Took the loop to roll it.")
Output:
Rolled: 3
Rolled: 1
Rolled: 6
Got a 6! Took the loop to roll it.
The loop always executes at least once because result starts as None, which is never equal to 6.
Using a Function with Recursion
For scenarios where the do-while pattern maps naturally to "try, then retry if needed":
def get_valid_age():
"""Keep asking until a valid age is provided."""
age = int(input("Enter your age (1-120): "))
if 1 <= age <= 120:
return age
print("Invalid age. Please try again.\n")
return get_valid_age() # Retry
age = get_valid_age()
print(f"Your age: {age}")
Output:
Enter your age (1-120): 0
Invalid age. Please try again.
Enter your age (1-120): 150
Invalid age. Please try again.
Enter your age (1-120): 25
Your age: 25
Python has a default recursion limit of ~1000 calls. If the user could potentially enter invalid input many times, the while True + break approach is safer.
Using Walrus Operator (Python 3.8+)
The walrus operator (:=) allows assignment within expressions, enabling compact do-while patterns:
while (line := input("Enter text ('quit' to stop): ")) != 'quit':
print(f"Processing: {line.upper()}")
print("Done!")
Output:
Enter text ('quit' to stop): hello
Processing: HELLO
Enter text ('quit' to stop): world
Processing: WORLD
Enter text ('quit' to stop): quit
Done!
Technically, this is a while loop with the assignment happening in the condition. If the first input is 'quit', the body won't execute, so it's not a true do-while. However, for many practical scenarios it achieves the desired effect.
For a true do-while guarantee (body always runs once), use while True + break.
Comparing with a Regular While Loop
To understand why do-while matters, compare these two approaches for reading until a sentinel value:
# Regular while loop: requires duplicating the initial read
data = input("Enter value: ")
while data != 'stop':
print(f"Got: {data}")
data = input("Enter value: ")
# Do-while emulation: no duplication
while True:
data = input("Enter value: ")
if data == 'stop':
break
print(f"Got: {data}")
The regular while loop requires the input statement twice (before the loop and inside it). The do-while pattern keeps it in one place, following the DRY (Don't Repeat Yourself) principle.
Practical Example: Menu System
A common real-world use case for do-while is a menu that should display at least once:
def show_menu():
print("\n===== Main Menu =====")
print("1. View profile")
print("2. Edit settings")
print("3. Help")
print("4. Exit")
return input("Choose an option: ")
while True:
choice = show_menu()
if choice == '1':
print("Displaying profile...")
elif choice == '2':
print("Opening settings...")
elif choice == '3':
print("Showing help documentation...")
elif choice == '4':
print("Goodbye!")
break
else:
print("Invalid option. Please try again.")
Output:
===== Main Menu =====
1. View profile
2. Edit settings
3. Help
4. Exit
Choose an option: 1
Displaying profile...
===== Main Menu =====
1. View profile
2. Edit settings
3. Help
4. Exit
Choose an option: 4
Goodbye!
Quick Comparison of Methods
| Method | Guarantees One Execution | Readability | Best For |
|---|---|---|---|
while True + break | ✅ | ✅ Excellent | Most do-while scenarios |
| Flag variable | ✅ | ✅ Good | Complex exit conditions |
| Condition variable | ✅ | 🔶 Moderate | Simple numeric/value conditions |
| Recursion | ✅ | 🔶 Moderate | Functional style, few retries |
| Walrus operator | ❌ (not always) | 🔶 Moderate | Compact one-liners (Python 3.8+) |
Conclusion
While Python doesn't have a native do-while loop, you can effectively emulate one using several patterns:
while Truewithbreakis the most Pythonic and widely recommended approach. It's clear, flexible, and guarantees the body executes at least once.- Flag variables are useful when exit conditions are complex or checked at multiple points in the loop body.
- Condition variables initialized to ensure first-iteration entry work well for simple numeric conditions.
- The walrus operator (Python 3.8+) offers concise syntax for input-processing loops.
For nearly all cases, the while True + break pattern is the best choice. It's immediately recognizable, easy to maintain, and avoids the code duplication that a regular while loop would require.