Syntax of Python Do-While
Here's the general syntax for a do-while loop in Python:
while True:
# code block
# ...
if condition:
break
In this syntax, the while True statement creates an infinite loop that will keep executing the code block until the break statement is encountered. The if statement inside the loop checks the condition, and if it's true, the break statement is executed, causing the loop to terminate.
It's important to note that Python doesn't have a built-in do-while loop like some other programming languages. However, we can simulate its behavior using a combination of while True and break statements as shown above.
Example of Do While Loop
Suppose we want to prompt the user to enter a positive number and keep asking until a positive number is provided.
Here's how we can implement this using a do-while loop:
Python
while True:
number = int(input("Enter a positive number: "))
if number > 0:
break
print("Invalid input! Please enter a positive number.")
print("You entered:", number)

You can also try this code with Online Python Compiler
Run Code
In this example, we start with a while True loop that will keep running until the break statement is encountered. Inside the loop, we prompt the user to enter a positive number using the input() function and convert the input to an integer using int().
We then check if the entered number is greater than 0 using an if statement. If the condition is true, we execute the break statement, which terminates the loop. If the condition is false, we print an error message indicating that the input is invalid and the loop continues to the next iteration.
After the loop ends, we print the positive number entered by the user.
Here's an example run of the program:
Enter a positive number: -5
Invalid input! Please enter a positive number.
Enter a positive number: 0
Invalid input! Please enter a positive number.
Enter a positive number: 10
You entered: 10
As you can see, the loop keeps prompting the user until a positive number is entered, demonstrating the behavior of a do while loop.
Frequently Asked Questions
Can a do-while loop have multiple conditions?
Yes, you can use logical operators like and or to combine multiple conditions in the if statement inside the loop.
Is it possible to have nested do-while loops in Python?
Yes, you can nest do while loops inside each other, just like you can with regular while loops or for loops.
When should I use a do-while loop instead of a regular while loop?
Use a do-while loop when you want the code block to execute at least once, regardless of the initial condition. Use a regular while loop when you want to check the condition before the first iteration.
Conclusion
In this article, we learned about the do-while loop in Python. We discussed the concept, syntax, and how it differs from a regular while loop. We also looked at an example that showed how to use a do-while loop to repeatedly prompt the user for input until a certain condition is met.