Tutorial 1: Introduction to Iteration and the for Loop

Learning Objective

Understand the concept of iteration and the basic syntax of the for loop.

1. What is Iteration? Why do we need Loops?

Imagine you are a teacher handing back graded tests to 30 students. Without a loop, you would have to write a separate instruction for every single student:

In programming, doing this is called hard-coding, and it is terrible practice. Why?

  1. It is repetitive (violates DRY - Don't Repeat Yourself).
  2. It is inflexible – what if you have 31 students today?
  3. It is error-prone – you might accidentally skip student 19.

Iteration is the programming solution to this. It is the process of repeating a block of code one time for each item in a collection (like a list of students) or a specific number of times.

Think of a for loop as an automated assembly line: the robot picks up the first item, processes it, picks up the second item, processes it, and continues until all items are processed.

2. The for Loop Syntax

In Python, the for loop is designed to iterate over iterable objects (sequences like strings, lists, tuples, and ranges).

Here is the anatomy of a for loop:

for variable_name in iterable_collection: # Indented code block (the "body" of the loop) # This runs once for each item in the collection.

Breaking it down:

3. Iterating Over Different Iterables

Let's see how the loop variable behaves with different data types.

A. Iterating over a List

The loop runs once for every element inside the list.

colors = ["red", "blue", "green"] for color in colors: print(f"My favorite color is {color}.")

Output:

My favorite color is red. My favorite color is blue. My favorite color is green.

B. Iterating over a String

Strings are sequences of characters. The loop runs once for every character.

word = "CAT" for letter in word: print(letter)

Output:

C A T

C. Iterating over a Tuple

Tuples work exactly like lists for iteration.

coordinates = (10, 20, 30) for coord in coordinates: print(coord * 2)

Output: 20, 40, 60

D. Advanced: Tuple Unpacking in Loops

If your list contains tuples, you can unpack them directly in the loop header.

students = [("Alice", 95), ("Bob", 87), ("Charlie", 92)] for name, score in students: print(f"{name} scored {score}%.")

4. The range() Function

Often, we need to run a loop a specific number of times, but we don't necessarily have a list of items. This is where range() comes in. range() generates a sequence of numbers on the fly.

Crucial rule: range() is exclusive on the upper bound. It stops before reaching the stop number.

Function Call Generated Sequence Explanation
range(stop) 0, 1, 2, ..., stop-1 Starts at 0 by default.
range(start, stop) start, start+1, ..., stop-1 Starts at start, stops before stop.
range(start, stop, step) start, start+step, ... Changes the increment (can use negative).

Visual Examples:

# Example 1: range(stop) - Default start is 0 for i in range(5): # Generates 0, 1, 2, 3, 4 print(f"Number: {i}") # Example 2: range(start, stop) for i in range(2, 6): # Generates 2, 3, 4, 5 print(i) # Example 3: range(start, stop, step) - Counting by 2s for i in range(0, 10, 2): # Generates 0, 2, 4, 6, 8 print(i) # Example 4: Negative step (Counting backwards) for i in range(10, 4, -2): # Generates 10, 8, 6 print(i)

💡 Pro-Tip: If you are ever confused about what a range() produces, convert it to a list to see it clearly: print(list(range(2, 10, 2))) -> [2, 4, 6, 8].

5. Common Pitfalls (And How to Avoid Them)

Beginners frequently make these mistakes. Read them carefully to save yourself time debugging!

  1. Forgetting the Colon (:)

    # WRONG for i in range(3) # <- Missing colon! print(i)
  2. Indentation Errors

    # WRONG: This will run ONCE after the loop finishes, not inside it. for i in range(3): print("Inside loop") print("Outside loop") # This is NOT indented!

    (Note: The first print runs 3 times. The second print runs 1 time).

  3. The "Off-by-One" Error

    # WRONG: Prints 1 to 9 (misses 10!) for i in range(1, 10): print(i) # RIGHT: Prints 1 to 10 for i in range(1, 11): print(i)
  4. Loop Variable Leakage

    for item in ["apple", "banana"]: pass print(item) # This will print 'banana'. Be careful not to rely on this!
  5. Modifying a List While Iterating Over It (Advanced Warning)

📝 Quiz: Check Your Understanding (Part 1)

Take a moment to answer these without running the code! Q1: What is the output of the following code?

for x in range(3, 7): print(x, end=" ")
Answer(B) 3 4 5 6

Q2: What does list(range(8, 1, -2)) return?

Answer(A) `[8, 6, 4, 2]`

Q3: (True/False) The code below will run perfectly.

for i in range(10) print(i)
AnswerFalse – missing colon and indentation.

💻 In-Tutorial Coding Exercises

Open your Python IDE or notebook. Write the code for the following challenges. Run them to see if they work!

Exercise 1 (Strings): Write a for loop that prints each character of your first name in reverse order.

Sample Solution
name = "John" for char in name[::-1]: print(char) # Output: n, h, o, J

Exercise 2 (Range – Summation): Write a for loop using range() to calculate and print the sum of all numbers from 1 to 50 (inclusive).

Sample Solution
total = 0 for num in range(1, 51): total += num print(f"The sum is: {total}") # 1275

Exercise 3 (Lists): Given cities = ["Paris", "London", "Tokyo", "New York"], print "I want to visit Paris!" etc.

Sample Solution
cities = ["Paris", "London", "Tokyo", "New York"] for city in cities: print(f"I want to visit {city}!")

Exercise 4 (Stepping): Print only the odd numbers between 0 and 20 (exclusive of 20).

Sample Solution
for num in range(1, 20, 2): print(num)

Exercise 5 (Unpacking): Given items = [("pencil", 1.50), ("book", 12.99), ("eraser", 0.75)], print "The [item] costs $[price].".

Sample Solution
items = [("pencil", 1.50), ("book", 12.99), ("eraser", 0.75)] for item, price in items: print(f"The {item} costs ${price}.")

📚 Homework Questions

These problems require you to combine everything you've learned. Write complete Python scripts for each.

Question 1: Factorial Calculator
Write a program that asks for a positive integer n and calculates n! using a for loop. Print the result.

Sample Answer
n = int(input("Enter a positive integer: ")) factorial = 1 for i in range(1, n+1): factorial *= i print(f"{n}! = {factorial}")

Question 2: Sum of Squares
Calculate and print the sum of squares from 1 to N.

Sample Answer
N = int(input("Enter N: ")) sum_sq = 0 for i in range(1, N+1): sum_sq += i*i print(f"Sum of squares = {sum_sq}")

Question 3: Vowel Counter
Count vowels (case‑insensitive) in a user‑input string.

Sample Answer
text = input("Enter a string: ") vowels = "aeiouAEIOU" count = 0 for ch in text: if ch in vowels: count += 1 print(f"Vowel count: {count}")

Question 4: Multiplication Table
Print the multiplication table for a given number from 1 to 10.

Sample Answer
num = int(input("Enter a number: ")) for i in range(1, 11): print(f"{num} x {i} = {num*i}")

Question 5: Reverse String Slicer (Challenge)
Build a reversed string without using [::-1].

Sample Answer
s = input("Enter a string: ") rev = "" for char in s: rev = char + rev print(rev)

Congratulations! You have now mastered the foundational concepts of the for loop. Understanding this tutorial perfectly is critical before moving on to while loops and flow control (Tutorials 2 & 3).