23  For Loops: Parzival’s Repetitive Quests

Today, we embark on a new adventure to master one of the most powerful spells in the Python realm: the for loop. Just as Parzival faced many trials in his quest for the Holy Grail, we often need to perform the same action multiple times in our code. The for loop is our magical key to efficiently conquering these repetitive tasks.

23.1 What is a For Loop?

Imagine Parzival needs to knock on the doors of 100 castles to find the Holy Grail. Writing the “knock on door” code 100 times would be tedious and inefficient. That’s where the for loop comes in handy. It allows us to repeat a set of instructions a specific number of times or for each item in a collection.

Here’s the basic structure of a for loop:

for item in sequence:
    # Code to be repeated

Let’s break this down:

  • for is the keyword that starts the loop
  • item is a variable that takes on the value of each element in the sequence
  • sequence is the collection of items we’re looping through
  • The indented code block after the colon : is what gets repeated

23.2 Your First For Loop: Knocking on Castle Doors

Let’s write a simple for loop to help Parzival knock on castle doors:

for castle_number in range(1, 6):
    print(f"Parzival knocks on castle number {castle_number}")

print("Parzival finished knocking!")

When you run this code, you’ll see:

Parzival knocks on castle number 1
Parzival knocks on castle number 2
Parzival knocks on castle number 3
Parzival knocks on castle number 4
Parzival knocks on castle number 5
Parzival finished knocking!

Here, range(1, 6) creates a sequence of numbers from 1 to 5 (remember, the end number is not included). The loop runs once for each number, with castle_number taking on each value in turn.

23.3 Looping Through Lists

We can also use for loops to iterate through lists. Let’s say Parzival has a list of magical items:

magical_items = ["Excalibur", "Holy Grail", "Magic Shield", "Enchanted Armor", "Wizard's Staff"]

for item in magical_items:
    print(f"Parzival wields the {item} with great power!")

print("All magical items have been used!")

This will output:

Parzival wields the Excalibur with great power!
Parzival wields the Holy Grail with great power!
Parzival wields the Magic Shield with great power!
Parzival wields the Enchanted Armor with great power!
Parzival wields the Wizard's Staff with great power!
All magical items have been used!

23.4 The Range Function: Parzival’s Training Regimen

The range() function is a powerful tool when working with for loops. It can take up to three arguments:

  • range(stop): Generates numbers from 0 to stop -1
  • range(start, stop): Generates numbers from start to stop -1
  • range(start, stop, step): Generates numbers from start to stop -1, incrementing by step

Let’s see how Parzival might use this in his training:

# Parzival's warm-up: 5 jumping jacks
print("Warm-up:")
for i in range(5):
    print(f"Jumping jack #{i+1}")

print("\nStrength training:")
# Parzival's strength training: lift weights from 10 to 50 pounds, increasing by 10
for weight in range(10, 51, 10):
    print(f"Lifting {weight} pounds")

print("\nCool-down:")
# Parzival's cool-down: count backwards from 5 to 1
for count in range(5, 0, -1):
    print(f"Cool-down stretch #{count}")

This will output:

Warm-up:
Jumping jack #1
Jumping jack #2
Jumping jack #3
Jumping jack #4
Jumping jack #5

Strength training:
Lifting 10 pounds
Lifting 20 pounds
Lifting 30 pounds
Lifting 40 pounds
Lifting 50 pounds

Cool-down:
Cool-down stretch #5
Cool-down stretch #4
Cool-down stretch #3
Cool-down stretch #2
Cool-down stretch #1

23.5 The Power of Accumulation: Counting Parzival’s Treasure

For loops are great for accumulating results. Let’s say Parzival is counting his treasure after a successful quest:

treasure_chests = [50, 100, 75, 200, 25]
total_gold = 0

for gold in treasure_chests:
    total_gold += gold

print(f"Parzival has accumulated {total_gold} gold coins on this quest!")

This will output:

Parzival has accumulated 450 gold coins on this quest!

23.6 Practice Time: Your For Loop Quests

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

  1. Create a list of 5 legendary weapons. Use a for loop to print a sentence about Parzival using each weapon.

  2. Use a for loop with range() to print the squares of numbers from 1 to 5.

  3. Create a list of enemies Parzival must face. Use a for loop to print how many experience points he gains from defeating each enemy (you decide the XP values).

  4. Use a for loop to calculate the sum of all numbers from 1 to 100 (this is Parzival’s endurance test).

Here’s a starting point for your quests:

# Quest 1: Legendary Weapons
legendary_weapons = ["Excalibur", "Mjolnir", "Gae Bolg", "Durandal", "Gungnir"]
# Your code here

# Quest 2: Square Numbers
# Your code here

# Quest 3: Defeating Enemies
enemies = ["Dragon", "Dark Knight", "Evil Wizard", "Goblin King", "Kraken"]
# Your code here

# Quest 4: Endurance Test
# Your code here

23.7 Common Bugs to Watch Out For

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

  1. Forgetting the colon: Always remember to put a colon : at the end of your for line.

  2. Incorrect indentation: The code block you want to repeat must be indented under the for statement. Incorrect indentation can change the meaning of your code.

  3. Off-by-one errors: Remember, range(1, 6) goes up to 5, not 6. If you need to include the last number, use range(1, 7).

  4. Modifying the loop variable: Avoid changing the loop variable (like i or item) within the loop. This can lead to unexpected behavior.

  5. Using break or continue incorrectly: These keywords can alter the flow of your loop. Make sure you understand their effects before using them.

23.8 Conclusion and Further Resources

You’ve now learned the art of repetition with for loops. This powerful tool will allow you to efficiently handle repeated tasks and iterate through collections of data, just as Parzival must repeat his training and face multiple challenges in his quest.

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

  1. Python’s official tutorial on for statements
  2. Real Python’s Python “for” Loops (Definite Iteration)
  3. W3Schools Python For Loops

Remember, mastering for loops is like honing your sword skills - it takes practice to become truly proficient. Keep coding, keep iterating, and soon you’ll be tackling complex programming quests with ease!