Chapter 3: Strings and Loops / Lesson 19

Do-While Pattern

Do-While Pattern in Python

Unlike some programming languages, Python doesn't have a built-in do-while loop. However, you can easily simulate this pattern using a while True loop with a break statement.

A do-while loop ensures that the code block executes at least once before checking the condition. This is useful for user input validation, menu systems, and operations that need to run at least one time.

Basic Do-While Pattern

The most common pattern uses while True with a break statement to exit:

do_while.py
while True: user_input = input("Enter 'quit' to exit: ") print(f"You entered: {user_input}") if user_input.lower() == "quit": break print("Loop ended")

Pattern 1: User Input Validation

This pattern ensures you always get valid input from the user:

validation.py
while True: age = input("Enter your age: ") if age.isdigit() and 0 <= int(age) <= 120: age = int(age) break print("Invalid input! Please enter a valid age (0-120).") print(f"You are {age} years old.")

Pattern 2: Menu System

Perfect for interactive menus that always show at least once:

menu.py
while True: print("\nMenu:") print("1. Option 1") print("2. Option 2") print("3. Quit") choice = input("Enter choice: ") if choice == "1": print("You selected Option 1") elif choice == "2": print("You selected Option 2") elif choice == "3": print("Goodbye!") break else: print("Invalid choice!")

Pattern 3: Process and Check

Execute code first, then check if you should continue:

process.py
attempts = 0 while True: attempts += 1 print(f"Attempt {attempts}") # Simulate some operation success = attempts >= 3 if success: print("Operation successful!") break print("Trying again...")

Alternative: Using a Flag Variable

Another approach uses a flag variable to control the loop:

flag.py
continue_loop = True while continue_loop: user_input = input("Enter 'stop' to quit: ") print(f"Processing: {user_input}") if user_input.lower() == "stop": continue_loop = False print("Done!")

When to Use Do-While Pattern

✅ Use Do-While When:

• You need to execute code at least once

• You're waiting for user input

• You need to validate input before proceeding

• You're implementing a menu or interactive system

⚠️ Be Careful Of:

• Infinite loops if you forget the break condition

• Logic errors that prevent the loop from ever exiting

• Making sure your exit condition is clear and reachable

Key Differences from Regular While Loop

The main difference is that the do-while pattern guarantees at least one execution:

difference.py
# Regular while - may not execute if condition is false count = 5 while count < 3: print(count) # Never executes # Do-while pattern - always executes at least once count = 5 while True: print(count) # Executes once if not (count < 3): break
🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...