for LoopUnderstand the concept of iteration and the basic syntax of the for loop.
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?
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.
for Loop SyntaxIn 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:
for: The keyword that starts the loop.variable_name: A temporary name you choose. In each iteration, this variable automatically takes the value of the next item in the collection.in: The keyword that connects the variable to the collection.iterable_collection: The sequence you want to go through (e.g., list, string, range).: (Colon): Marks the end of the loop header. Never forget this!Let's see how the loop variable behaves with different data types.
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.
Strings are sequences of characters. The loop runs once for every character.
word = "CAT"
for letter in word:
print(letter)
Output:
C
A
T
Tuples work exactly like lists for iteration.
coordinates = (10, 20, 30)
for coord in coordinates:
print(coord * 2)
Output: 20, 40, 60
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}%.")
range() FunctionOften, 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].
Beginners frequently make these mistakes. Read them carefully to save yourself time debugging!
Forgetting the Colon (:)
SyntaxError: invalid syntaxfor statement line.# WRONG
for i in range(3) # <- Missing colon!
print(i)
Indentation Errors
IndentationError: expected an indented block or code runs without looping (if the line isn't indented).# 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).
The "Off-by-One" Error
range(stop) stops before stop. If you want 1 through 10, use range(1, 11).# 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)
Loop Variable Leakage
for item in ["apple", "banana"]:
pass
print(item) # This will print 'banana'. Be careful not to rely on this!
Modifying a List While Iterating Over It (Advanced Warning)
for item in my_list[:]:.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=" ")
Q2: What does list(range(8, 1, -2)) return?
[8, 6, 4, 2][8, 6, 4, 2, 0][8, 6, 4]Q3: (True/False) The code below will run perfectly.
for i in range(10)
print(i)
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.
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).
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.
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).
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].".
items = [("pencil", 1.50), ("book", 12.99), ("eraser", 0.75)]
for item, price in items:
print(f"The {item} costs ${price}.")
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.
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.
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.
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.
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].
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).