This lesson on Python For Loops is hands-on and example-driven. You will learn how to use Python for loops to execute a block of code a fixed number of times by iterating over sequences like ranges and strings. You will also master the use of the range() function and control flow keywords (break and continue) to manage loop execution. This skill is fundamental for processing data sets and performing repetitive tasks efficiently.
What You'll Be Able To Do
- Construct a for loop to iterate over a fixed numerical range using the range() function.
- Apply the step parameter within range() to count forwards or backwards by specific increments.
- Iterate directly over characters within a string sequence using a for loop.
- Implement the continue keyword to skip specific iterations based on a condition.
- Use the break keyword to immediately terminate a loop when a condition is met.
Detailed Concept Walkthrough
1. For Loop Fundamentals
A for loop executes a code block repeatedly for a fixed number of times by processing items in an iterable sequence (like lists, strings, or ranges). This structure is ideal when the number of repetitions is known beforehand.
- Mechanism: The loop assigns the next item from the iterable sequence to the loop variable (e.g., 'x') in each iteration until the sequence is exhausted.
- Syntax Rule: The loop body must be indented after the colon following the 'for...in...' statement to define the block of code that repeats.
- Best Practice: Choose descriptive names for the loop variable unless iterating over simple numerical ranges (where 'i' or 'x' is common).
credit_card = "1234-5678"
for x in credit_card:
print(x) # Prints each character sequentially
Key Takeaway: For loops are designed for definite iteration over any iterable object.
2. Controlling Iteration Count with Range
The built-in range() function generates a sequence of numbers, making it the primary tool for controlling how many times a for loop runs numerically. It is memory efficient as it generates numbers on demand.
- Mechanism: range(start, stop, step) generates numbers starting at 'start' (inclusive) up to, but not including, 'stop' (exclusive).
- Execution Flow: To count to 10 starting at 1, you must set the stop value to 11 because the stop value is always exclusive.
- Best Practice: Use the optional 'step' parameter (positive or negative) to count by increments (e.g., by 2s) or to count backwards.
# Count 1 to 10 by 2s
for x in range(1, 11, 2):
print(x)
# Count backwards 10 to 1
for x in reversed(range(1, 11)):
print(x)
Key Takeaway: Remember the 'stop' value in range() is exclusive; always add one to your desired endpoint.
3. Break and Continue Keywords
Break and continue are keywords used inside loops to alter the standard flow of execution, allowing you to skip iterations or exit the loop prematurely based on runtime conditions.
- Mechanism: 'continue' immediately stops the current iteration and moves execution to the next item in the sequence.
- Mechanism: 'break' immediately terminates the entire loop, and execution resumes at the first line of code following the loop body.
- Best Practice: Use 'break' when finding a required item (efficiency); use 'continue' when skipping unwanted data points (filtering).
for x in range(1, 21):
if x == 13:
continue # Skip 13
if x == 15:
break # Stop loop entirely
print(x)
Key Takeaway: Continue skips one cycle; break exits the entire loop structure.
Topics Covered in Python For Loops
- For Loop Definition (0:00 - 0:30) — For loops execute a block of code a fixed number of times over any iterable sequence.
- Basic Range Syntax (0:30 - 1:00) — The basic syntax uses range(start, stop) where the stop number is exclusive.
- Counting Backwards (1:00 - 1:45) — Counting backwards can be achieved by enclosing the range function within the reversed() function.
- Using Step Parameter (1:45 - 2:20) — The optional step parameter allows counting by increments other than one, such as by twos or threes.
- Iterating Over Strings (2:20 - 3:00) — For loops can iterate directly over a string, processing each character sequentially.
- Continue Keyword (3:00 - 3:50) — The continue keyword skips the current iteration and moves to the next item in the sequence.
- Break Keyword (3:50 - 4:20) — The break keyword immediately terminates the entire loop execution.
- Loop Comparison Summary (4:20 - 4:45) — For loops are best for fixed execution counts, while while loops are better for conditional or potentially infinite execution.
Python Cheat Sheet
-
for x in iterable:— Iterate over items in a sequencefor char in "data": print(char) -
range(start, stop)— Generates numbers from start to exclusive stopfor x in range(1, 11): print(x) -
range(start, stop, step)— Generates numbers using specified incrementfor x in range(1, 11, 2): print(x) -
reversed(range(...))— Iterates through a range backwardsfor x in reversed(range(1, 11)): print(x) -
continue— Skips the current iteration immediatelyif x == 13: continue -
break— Exits the entire loop immediatelyif x == 13: break
Comparison Table
| Feature | For Loop | While Loop |
|---|---|---|
| Primary Use Case | Fixed number of iterations. | Condition-based execution. |
| Iteration Source | Iterates over sequences/iterables. | Executes until a condition is False. |
| Typical Scenario | Processing all items in a list. | Accepting continuous user input. |
Common Pitfalls
- Mistake: Forgetting that the range() stop value is inclusive. Avoid: Always set the stop value one higher than the desired final number.
- Mistake: Using break when you only intend to skip a single item. Avoid: Use continue if you want the loop to proceed to the next iteration.
- Mistake: Not indenting the code block inside the loop. Avoid: Ensure all code meant to repeat is indented four spaces after the colon.
- Mistake: Trying to count backwards without using reversed() or a negative step. Avoid: Use reversed(range(start, stop)) for simple countdowns.
FAQs
- Can I use a for loop to iterate over something that isn't a string or a range? Yes, you can iterate over anything considered iterable, such as lists, tuples, dictionaries, and file objects.
- What happens to the loop variable (x) after the loop finishes? The loop variable retains the value of the last item it processed before the loop completed or was broken.
- Why are for loops better than while loops for fixed counts? For loops handle the initialization, condition checking, and increment/decrement automatically based on the iterable, making the code cleaner and less error-prone for definite iteration.