For Loops

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Introduction to For Loops

A for loop allows you to repeat a block of code multiple times. It's like giving instructions to do something over and over with different items in a collection.

Here's the basic syntax of a for loop in Python:

for item in collection: # Code to execute for each item

Let's see a simple example with a list of Codémon names:

codemons = ["Aquachu", "Pyrochu", "Florachu"] for codemon in codemons: print("I choose you,", codemon, "!")

In this example, we base the loop on the codemons list with 3 names. The loop goes through each name one by one, and the code inside the loop runs for each name.

Exercise 2 — For Loop Syntax

Which of the following is the correct syntax for a for loop in Python?

Options
• for item in collection: # code block
• for (item in collection) { # code block }
• for item = collection: # code block
• for each item in collection: # code block

Hint : Remember : the correct syntax for a for loop in Python is for followed by a variable name, the keyword in, the collection, and a colon. The body of the loop must be indented.

Exercise 3 — Iterating Over Lists

One of the most common uses of for loops is to iterate over items in a list. Each time the loop runs, the loop variable takes the value of the next item in the list.

levels = [5, 10, 15, 20] # Loop through each level for level in levels: print("Codémon at level", level)

Within the loop, you can basically do whatever you want, it's normal Python code. You can print the value, perform calculations, or even modify other variables.

powers = [10, 20, 30, 40] # Calculate and print double the power for each value for power in powers: doubled_power = power * 2 print("Original power:", power, "Doubled:", doubled_power)

Loop Variable Scope

The loop variable (like 'codemon', 'level', or 'power' in our examples) is created when the loop starts. It continues to exist after the loop ends, containing the last value it was assigned during the loop.

Exercise 4 — Complete the For Loop

Complete the for loop to print each Codémon type with an appropriate message.

Hint : The syntax for a for loop requires the 'for' keyword, followed by a variable name, then 'in', and finally the collection to iterate over.

Exercise 5 — Using range() with For Loops

The range() function is commonly used with for loops to repeat an action a specific number of times or to generate a sequence of numbers.

# range(stop) - Creates a sequence from 0 to stop-1 print("range(5):") for i in range(5): print(i) # range(start, stop, step) - Creates a sequence with a specific step print("range(1, 10, 2):") for i in range(0, 10, 2): print(i)

range() can take one, two, or three parameters: 1. One parameter: range(stop) will start at 0 and stop at the stop - 1 2. Two parameters: range(start, stop) will start at the start number and stop at stop - 1 3. Three parameters: range(start, stop, step) starts at start, stops at stop - 1, and increments by step each time.

Exercise 6 — Match Range Expressions

Match each range expression with the sequence of numbers it generates.

Items to match
• range(5)
• range(2, 6)
• range(1, 10, 2)
• range(10, 5, -1)
Definitions
• 0, 1, 2, 3, 4
• 2, 3, 4, 5
• 1, 3, 5, 7, 9
• 10, 9, 8, 7, 6

Exercise 7 — Understanding Range Parameters

Which range expression would generate the sequence: 2, 4, 6, 8, 10?

Options
• range(1, 12, 2)
• range(2, 10, 2)
• range(2, 11, 2)
• range(0, 10, 2)

Hint : When using range(start, stop, step), remember that it includes start but excludes stop.

Exercise 8 — Tracing Loop Variable Values

Consider the following code:

items = ["potion", "revive", "codeball"] for item in items: print(item)

What will be the entire output of this code?

Options
• "potion", "revive", "codeball"
• "codeball", "revive", "potion"
• "item", "item", "item"
• There is going to be an error

Hint : Remember that in 'for item in items', the variable 'item' takes on each value from the list in order.

Exercise 9 — Advanced Range Expressions

Match each range expression with the sequence it generates.

Items to match
• range(10, 0, -2)
• range(5, 20, 5)
• range(3, 4)
• range(0, -5, -1)
Definitions
• 10, 8, 6, 4, 2
• 5, 10, 15
• 3
• 0, -1, -2, -3, -4

Exercise 10 — Accumulating Values in Loops

A common pattern with loops is to accumulate or calculate a result based on all items in a collection. For example, summing numbers.

Example: Summing values in a list

powers = [45, 60, 35, 50] # Initialize the total to 0 total_power = 0 # Add each power to the total for power in powers: total_power = total_power + power print("Total power:", total_power)

Accumulation Pattern

The accumulation pattern generally follows these steps: 1. Initialize an accumulator (like total_power = 0 or an empty list) 2. Loop through the collection 3. Update the accumulator with each item 4. After the loop, the accumulator contains the final result

Exercise 11 — What Will This Loop Print?

What will be the output of the following code?

elements = ["water", "fire", "grass"] result = "" for element in elements: result = result + element[0] print(result)
Options
• wfg
• WFG
• waterfiregrass
• WATERFIREGRASS

Hint : Looping over a list using a in statement allows you to access each element directly.

Exercise 12 — Loops with Indices

Another way to access indices AND values of the list is using range() with the length of the list:

codemons = ["Aquachu", "Pyrochu", "Florachu"] for i in range(len(codemons)): print("Position", i, "contains", codemons[i])

When to Use Indices

Use indices when you need to: - Know the position of each item - Access multiple items in relation to the current item (like the next or previous item) - Modify the original list while iterating

Exercise 13 — Working with Indices

Complete the code to print each Codémon's name along with its power level using indices.

Hint : When using indices, range(len(list)) creates a sequence of indices from 0 to the length of the list minus 1. You can then use these indices to access corresponding elements in multiple lists.

Exercise 14 — Analyzing Loop Behavior

What will be the final value of result after this code executes?

numbers = [5, 2, 8, 1, 7] result = 0 for i in range(len(numbers)): if i % 2 == 0: # If index is even result += numbers[i]
Options
• 20
• 23
• 15
• 10

Hint : In this exercise we loop through the whole list but a condition kind of filter what we add to the result.

Exercise 15 — Three Ways to Use For Loops

You've learned three different techniques for using for loops in Python. Each technique is useful in different situations. Let's review them:

Technique 1: Looping Directly Over a List

# Technique 1: Direct iteration over list codemons = ["Aquachu", "Pyrochu", "Florachu"] for codemon in codemons: print(codemon)

Technique 2: Looping with range()

# Technique 2: Using range() to repeat N times # Repeat 5 times for i in range(5): print("Training session", i + 1)

Technique 3: Looping with range(len())

# Technique 3: Using range(len()) to access indices names = ["Aquachu", "Pyrochu", "Florachu"] powers = [75, 80, 70] for i in range(len(names)): print("Position", i, ":", names[i], "with power", powers[i])

Quick Decision Guide

- Need only values? → Use for item in list - Need to repeat N times? → Use for i in range(N) - Need indices or multiple lists? → Use for i in range(len(list))

Exercise 16 — Codémon Challenge - Training Session Analyzer

Welcome to the Training Session Analyzer! You need to analyze the performance of your Codémon team during training. Your tasks: 1. Loop through each Codémon name and simulate 3 training rounds for each one. Display which Codémon is training and which round it is. (Hint: like nested if statements, you can nest loops inside other loops!) 2. Loop through both the names and experience_gained lists using indices to display how much experience each Codémon gained

Starter code
print("=== TRAINING SESSION ANALYZER ===") codemon_names = ["Aquachu", "Pyrochu", "Florachu"] experience_gained = [150, 200, 175] # Task 1: Loop through each Codémon and simulate 3 training rounds print("\n--- Training Sessions ---") # Task 2: Display experience gained by each Codémon using indices print("\n--- Experience Report ---")
Back to the course