Alternatives to “do while” loops in Python

In Python, the “do while” loop, commonly found in other programming languages, is not explicitly available. However, Python provides alternative constructs that achieve similar functionality. In this article, we’ll focus on the while loop and the while True idiom, showcasing practical examples to illustrate their usage.

The Traditional “do while” Loop in Other Languages
In languages like C, C++, and Java, the “do while” loop has the following structure:

do {
    // Code to be executed
} while (condition);

This loop executes the code block at least once, and then it continues to execute as long as the specified condition is true.

The Python “while” Loop

In Python, the standard while loop allows us to mimic the “do while” loop. Its structure is as follows:

while condition:
    # Code to be executed

The key difference is that the code block is executed only if the initial condition is true. If the condition is false from the beginning, the code block will not be executed at all.

Using “while True” as an Infinite Loop

To mimic the behaviour of a “do while” loop, where the loop body always executes at least once, we can use the while True idiom. This creates an infinite loop that can be exited using a break statement.

while True:
    # Code to be executed at least once

    # Condition to break the loop
    if some_condition:
        break

Here, the loop runs indefinitely until the specified condition (some_condition) is met, triggering the break statement to exit the loop.

Practical Examples

Example 1: User Input Validation

while True:
    user_input = input("Enter a positive number: ")

    try:
        number = float(user_input)
        if number > 0:
            break
        else:
            print("Please enter a positive number.")
    except ValueError:
        print("Invalid input. Please enter a valid number.")

This example ensures that the user inputs a positive number and keeps prompting until a valid input is provided.

Example 2: Menu Driven Program

while True:
    print("1. Option 1")
    print("2. Option 2")
    print("3. Exit")

    choice = input("Enter your choice: ")

    if choice == "1":
        # Code for option 1
        pass
    elif choice == "2":
        # Code for option 2
        pass
    elif choice == "3":
        break
    else:
        print("Invalid choice. Please enter a valid option.")

This example creates a simple menu-driven program that continues to execute until the user chooses to exit.

Please note that some people will tell you that while True: is a bad idea, based on the fact that you can inadvertently create an infinite loop which can’t be exited. However, context is everything and there are plenty of situations where using while True: is a perfectly valid choice.

Conclusion

While Python doesn’t have a “do while” loop, the combination of while and while True can effectively replicate its behaviour. By using these constructs along with the break statement, we can create versatile and expressive loops that cater to various programming scenarios.

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *