24  While Loops: Parzival’s Persistent Quests

In our last lesson, we mastered the for loop. Today, we embark on a new adventure to learn another powerful looping construct: the while loop. Just as Parzival must persist in his quest until he finds the Holy Grail, a while loop continues to execute as long as a certain condition is true.

24.1 What is a While Loop?

Imagine Parzival searching for the Holy Grail. He doesn’t know how many attempts it will take, but he knows he must keep searching until he finds it. This is where a while loop comes in handy. It allows us to repeat a set of instructions as long as a certain condition remains true.

Here’s the basic structure of a while loop:

while condition:
    # Code to be repeated

Let’s break this down:

  • while is the keyword that starts the loop
  • condition is an expression that evaluates to either True or False
  • The indented code block after the colon : is what gets repeated as long as the condition is True

24.2 Your First While Loop: Parzival’s Grail Quest

Let’s write a simple while loop to simulate Parzival’s search for the Holy Grail:

import random

grail_found = False
days_searching = 0

while not grail_found:
    days_searching += 1
    if random.randint(1, 10) == 1:  # 1 in 10 chance of finding the Grail each day
        grail_found = True

print(f"Huzzah! Parzival found the Holy Grail after {days_searching} days!")

This code will output something like:

Huzzah! Parzival found the Holy Grail after 7 days!

(The number of days will vary each time you run the code due to the random chance.)

In this example, the loop continues as long as grail_found is False. Each “day”, there’s a 1 in 10 chance of finding the Grail. When the Grail is found, grail_found becomes True, and the loop ends.

24.3 While Loops with Counter Variables

Often, we use a counter variable to keep track of how many times a loop has run. Let’s see how Parzival might use this in his training:

pushup_count = 0

while pushup_count < 10:
    pushup_count += 1
    print(f"Parzival does pushup #{pushup_count}")

print("Training complete! Time for a quest!")

This will output:

Parzival does pushup #1
Parzival does pushup #2
Parzival does pushup #3
Parzival does pushup #4
Parzival does pushup #5
Parzival does pushup #6
Parzival does pushup #7
Parzival does pushup #8
Parzival does pushup #9
Parzival does pushup #10
Training complete! Time for a quest!

24.4 The Power of User Input in While Loops

While loops are great for creating interactive programs that continue until the user decides to stop. Let’s create a simple game where Parzival guesses a number:

import random

secret_number = random.randint(1, 100)
guess = 0
attempts = 0

print("Parzival must guess the secret number between 1 and 100!")

while guess != secret_number:
    guess = int(input("Enter your guess, Parzival: "))
    attempts += 1
    
    if guess < secret_number:
        print("Too low! The number is higher.")
    elif guess > secret_number:
        print("Too high! The number is lower.")

print(f"Congratulations, Parzival! You found the secret number {secret_number} in {attempts} attempts!")

This game will continue until Parzival (the user) correctly guesses the secret number.

24.5 The ‘Break’ and ‘Continue’ Statements

Sometimes, we need more control over our loops. Python provides two special statements for this:

  1. break: Immediately exits the loop
  2. continue: Skips the rest of the current iteration and moves to the next one

Let’s see how Parzival might use these in his quest:

import random

dragon_power = 100
parzival_strength = 20

print("Parzival faces the mighty dragon!")

while dragon_power > 0:
    print(f"Dragon power: {dragon_power}, Parzival strength: {parzival_strength}")
    
    if parzival_strength <= 0:
        print("Parzival is too weak to continue. He must retreat!")
        break
    
    damage = random.randint(1, parzival_strength)
    dragon_power -= damage
    print(f"Parzival deals {damage} damage to the dragon!")
    
    if dragon_power <= 50 and random.random() < 0.2:  # 20% chance if dragon's below 1/2 health
        print("The dragon flies away to recover. Parzival must wait for another day.")
        break
    
    parzival_strength -= 1

if dragon_power <= 0:
    print("Parzival has slain the dragon! Victory!")
else:
    print("The dragon lives to fight another day. Parzival will return stronger!")

This code simulates a battle between Parzival and a dragon, using break to end the battle if Parzival becomes too weak, and continue to simulate the dragon occasionally flying away.

24.6 Practice Time: Your While Loop Quests

Now it’s your turn to wield the power of while loops. Complete these quests to prove your mastery:

  1. Create a while loop that simulates Parzival climbing a tower. He climbs 2-5 steps at a time (randomly), and the tower is 50 steps high. Print his progress as he climbs.

  2. Write a program that asks the user (Parzival) to guess a magic word. Use a while loop to keep asking until they guess correctly.

  3. Simulate a battle between Parzival and a series of enemies. Parzival starts with 100 health, and each enemy does 10-20 damage. See how many enemies Parzival can defeat before his health reaches 0.

  4. Create a simple text-based menu system for Parzival’s adventures. Use a while loop to keep showing the menu until the user chooses to quit.

Here’s a starting point for your quests:

import random

# Quest 1: Climbing the Tower
tower_height = 50
parzival_position = 0
# Your code here

# Quest 2: Guessing the Magic Word
magic_word = "Excalibur"
# Your code here

# Quest 3: Parzival's Battle
parzival_health = 100
enemies_defeated = 0
# Your code here

# Quest 4: Adventure Menu
# Your code here

24.7 Common Bugs to Watch Out For

As you practice your while loop skills, beware of these common pitfalls:

  1. Infinite loops: Make sure your condition will eventually become False, or use a break statement to exit the loop.

  2. Off-by-one errors: Be careful when using counters. Make sure your loop condition matches your intention.

  3. Forgetting to update the loop condition: If you’re using a variable in your condition, make sure it’s updated inside the loop.

  4. Incorrect indentation: Remember, everything that should repeat must be indented under the while statement.

  5. Using = instead of == in the condition: = is for assignment, == is for comparison.

24.8 Conclusion and Further Resources

You’ve now mastered the art of while loops. This powerful tool allows you to create flexible, responsive code that can adapt to changing conditions, just as Parzival must adapt to the challenges he faces on his quests.

To further enhance your while loop skills, check out these excellent resources:

  1. Python’s official tutorial on while statements
  2. Real Python’s Python “while” Loops (Indefinite Iteration)
  3. W3Schools Python While Loops

Remember, mastering while loops is like developing the persistence needed for a long quest - it takes practice and patience. Keep coding, keep iterating, and soon you’ll be creating complex, interactive programs with ease!