3.3 while Loops

3.3 while Loops

Learning the while loop, which executes a block of code repeatedly as long as a specific condition remains true, and how to avoid infinite loops.

The `while` loop executes a block of code as long as a specific condition is `True`. The condition is checked at the beginning of each iteration. If the condition becomes `False`, the loop terminates.

Syntax

`while condition:\n # Code that executes as long as the condition is True`

When to Use while vs. for

  • `for` loop: Ideal when you know in advance how many times you want to repeat the code, or when you want to iterate over all the items of a specific collection (e.g., list, string).
  • `while` loop: Ideal when the number of iterations is unknown and depends on a condition that may change during the loop's execution. Examples include waiting for user input, processing data until a specific result is achieved, or running a game until the player decides to stop.

The else Statement in while Loops

Similar to `for` loops, `while` loops can also have an `else` clause. The `else` code block is executed when the `while` condition becomes `False` and the loop terminates normally (i.e., not through a `break` statement).
# Example 1: while loop with a counter
counter = 0
print("Incrementing counter with while:")
while counter < 5:
    print(f"The counter is: {counter}")
    counter += 1 # We increment the counter to avoid an infinite loop

print("The while loop has finished.")

print("-" * 30)

# Example 2: while loop for user input (simulation)
answer = ""
# Simulate user input with a list of answers
test_answers = ["maybe", "no", "yes"] 
print("Question game (type 'yes' to continue, 'no' to exit):")

while answer.lower() != "yes":
    if test_answers:
        answer = test_answers.pop(0) # Get the next answer from the list
        print(f"Enter answer: {answer}")
    else:
        # If the list is empty, we stop to avoid an infinite loop
        print("The list of test answers is empty.")
        break

    if answer.lower() == "no":
        print("Okay, stopping the game.")
        break # We use 'break' to exit the loop
    elif answer.lower() != "yes":
        print("Invalid answer. Please type 'yes' or 'no'.")

print("Continuing program flow!")

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.