In any programming language, including Python, loops are essential for many purposes like iterating over sequences, running repetitive tasks, and handling dynamic data structures. If you have been using PythonCentral for learning Python, you would have realized that Python gives you "for" and "while" loops but not a built-in "do-while loop". While the do-while loop comes in-built in other programming languages like C, JavaScript, and Java, Python is an exception.
At PythonCentral, we will teach you how to simulate a do-while loop using a simple "while" loop but with a specific structure. Get. Set. Learn!
What is a "Do-While" Loop?
A "do-while" loop runs the loop body at least once before checking the condition. Let us take an example syntax to understand better. A typical do-while loop in C language looks like this:
int x = 0; do { printf("Iteration: %d", x); x++; } while (x < 5);
While we learnt that Python does not have a direct approach for do-while, it still lets us simulate one using a while loop.
How to Simulate a Do While Loop in Python
To simulate a do-while loop in Python, let us use a "while" loop with a break condition inside the loop body. Here is how you can write a Python code for the same example written in C language earlier:
x = 0 while True: print(f"Iteration: {x}") x += 1 if x >= 5: break
Let us break down this code for you to understand better. The loop executes at least once, because the condition is "True" initially. Inside the loop, we performed the required operation. We then checked the exit condition i.e., x>=5, and break out when met.
Use Cases of Do While Loops in Python
How to Validate Input with Python Do While
One of the most common use cases for a do-while loop is validating user input. Here is one sample to validate input:
while True: number = input("Enter a number between 1 and 10: ") if number.isdigit() and 1 <= int(number) <= 10: break print("Invalid input. Try again.")
Build Menu Driven Programs
Here is an example syntax to build menu-driven programs.
while True: print("1. Start") print("2. Settings") print("3. Exit") choice = input("Enter your choice: ") if choice == "3": print("Exiting...") break
API Polling with Python
If you want to check the status of API, here is how you can do it with a do-while loop:
import time import random while True: status = random.choice(["processing", "completed"]) print(f"Checking API status: {status}") if status == "completed": break time.sleep(2) # Simulate delay
Do While Loop Best Practices
Now that we have understood the basics and some example syntaxes, let us learn how to write meaningful or beautiful code.
- Always include a break condition to avoid infinite loops.
- Use meaningful conditions to ensure readability.
- Ensure the loop body executes at least once before checking conditions.
- Consider alternative approaches like recursion for certain cases.
Wrapping Up
Python does not have a native do-while loop? Not a problem. We now know how to simulate a do-while loop in Python by using a while loop with a break condition. Use this loop for menu-driven programs, API polling mechanisms, input validation, and many more use cases. By understanding Python loop constructs, you can write efficient, flexible, and error-free code for a lot of applications. Let us know what you built with Python do while loop in comments.