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 loopcondition
is an expression that evaluates to eitherTrue
orFalse
- The indented code block after the colon
:
is what gets repeated as long as the condition isTrue
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
= False
grail_found = 0
days_searching
while not grail_found:
+= 1
days_searching if random.randint(1, 10) == 1: # 1 in 10 chance of finding the Grail each day
= True
grail_found
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:
= 0
pushup_count
while pushup_count < 10:
+= 1
pushup_count 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
= random.randint(1, 100)
secret_number = 0
guess = 0
attempts
print("Parzival must guess the secret number between 1 and 100!")
while guess != secret_number:
= int(input("Enter your guess, Parzival: "))
guess += 1
attempts
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:
break
: Immediately exits the loopcontinue
: 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
= 100
dragon_power = 20
parzival_strength
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
= random.randint(1, parzival_strength)
damage -= damage
dragon_power 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
-= 1
parzival_strength
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:
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.
Write a program that asks the user (Parzival) to guess a magic word. Use a while loop to keep asking until they guess correctly.
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.
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
= 50
tower_height = 0
parzival_position # Your code here
# Quest 2: Guessing the Magic Word
= "Excalibur"
magic_word # Your code here
# Quest 3: Parzival's Battle
= 100
parzival_health = 0
enemies_defeated # 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:
Infinite loops: Make sure your condition will eventually become
False
, or use abreak
statement to exit the loop.Off-by-one errors: Be careful when using counters. Make sure your loop condition matches your intention.
Forgetting to update the loop condition: If you’re using a variable in your condition, make sure it’s updated inside the loop.
Incorrect indentation: Remember, everything that should repeat must be indented under the
while
statement.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:
- Python’s official tutorial on while statements
- Real Python’s Python “while” Loops (Indefinite Iteration)
- 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!