This lesson on Python For Loops is hands-on and example-driven. You will construct Python for loops to iterate over sequences, ranges, and strings for a predetermined number of cycles. You will control loop execution flow using step values, reverse sequences, and loop control keywords like continue and break.
What You'll Be Able To Do
- Construct standard for loops using the range() function with defined start and stop bounds.
- Apply custom step intervals and the reversed() function to iterate backwards or skip values.
- Iterate directly over sequence elements such as individual characters in a string.
- Bypass specific iterations using the continue keyword based on conditional checks.
- Terminate loop execution immediately using the break keyword upon meeting a exit condition.
Detailed Concept Walkthrough
1. Basic For Loop and Range Syntax
A for loop repeats a block of code a fixed number of times by binding an iterator variable to each value in an iterable sequence sequentially.
- Mechanism: The
forstatement assigns the current element to a target variable (e.g.,xorcounter) and runs the indented code block once per element until exhaustion. - Under the Hood: The
range(start, stop)function produces integers starting atstartand ending atstop - 1. The second parameter is strictly exclusive. - Syntax Rule: All statements intended to run inside the loop must be indented beneath the loop header, while code aligned with
forexecutes only after the loop completes.
# Count from 1 up to 10
for x in range(1, 11):
print(x)
# Code outside the loop executes after completion
print("Counting finished!")
Key Takeaway: The stop parameter in Python's range function is always exclusive, requiring n+1 to include n.
2. Step Intervals and Reverse Traversal
Loop progression can skip elements at fixed intervals or run backward using step parameters and iterator wrappers.
- Mechanism: Providing a third argument to
range(start, stop, step)changes the increment size between successive integers. - Execution Flow: Wrapping a range call within
reversed()traverses the generated sequence in reverse order without modifying the underlying bounds logic. - Best Practice: Use
stepto process every Nth item cleanly rather than maintaining an external index counter or manual increments.
# Count from 10 down to 1
for x in reversed(range(1, 11)):
print(x)
print("Happy New Year!")
# Count by increments of 2 (1, 3, 5, 7, 9)
for x in range(1, 11, 2):
print(x)
Key Takeaway: Modify iteration order and step sizes cleanly with reversed() and the step argument.
3. String Iteration
Strings in Python are native iterables, allowing loops to process text character-by-character directly.
- Mechanism: Directly supplying a string as the iterable target causes the loop variable to hold each individual character sequentially, including symbols and whitespace.
- Under the Hood: The loop accesses characters sequentially from index 0 to length - 1 without requiring manual index lookups.
- Best Practice: Iterate over strings directly when inspecting or transforming individual characters such as digits, delimiters, or tokens.
credit_card = "1234-5678-9012-3456"
# Iterate over each character in the string
for x in credit_card:
print(x)
Key Takeaway: Pass any string directly into a for loop to evaluate or process it character-by-character.
4. Loop Control with Continue and Break
The continue and break keywords dynamically alter execution flow by skipping iterations or halting loop execution entirely.
- Mechanism: The
continuestatement aborts the current iteration immediately and jumps to the next cycle in the loop sequence. - Execution Flow: The
breakstatement instantly halts the entire loop, transferring control directly to the first statement following the loop block. - Best Practice: Use
continueto filter out unwanted items early andbreakto exit early once a search target or terminating condition is found.
# Skip unlucky number 13 using continue
for x in range(1, 21):
if x == 13:
continue
print(x)
# Stop iteration entirely upon reaching 13 using break
for x in range(1, 21):
if x == 13:
break
print(x)
Key Takeaway: Use continue to skip a specific cycle and break to terminate the entire loop immediately.
Topics Covered in Python For Loops
- For Loop Basics (0:00 - 0:35) — The instructor defines for loops and demonstrates counting to 10 with range.
- Reverse and Step Iteration (0:36 - 1:05) — Counting backwards with reversed and skipping numbers using step intervals are covered.
- String Iteration (1:06 - 1:35) — Character-by-character iteration over a formatted credit card string is shown.
- Continue and Break (1:36 - 2:10) — The instructor demonstrates skipping numbers with continue and terminating loops with break.
- For vs While Loops (2:11 - 2:40) — A comparison highlights when to use fixed for loops versus indefinite while loops.
Python Cheat Sheet
-
for x in range(start, stop):— Iterates from start up to stop minus onefor x in range(1, 11): print(x) -
reversed(range(start, stop))— Reverses the direction of the range sequencefor x in reversed(range(1, 11)): print(x) -
range(start, stop, step)— Iterates by custom increment defined by stepfor x in range(1, 11, 2): print(x) -
for char in string:— Iterates over every character in a stringfor x in credit_card: print(x) -
continue— Skips the remainder of the current iterationif x == 13: continue -
break— Exits the loop entirely and immediatelyif x == 13: break
Comparison Table
| Feature / Construct | For Loop | While Loop |
|---|---|---|
| Execution Count | Fixed, predetermined number of times | Indefinite or potentially infinite iterations |
| Primary Use Case | Iterating over sequences and ranges | Awaiting conditions like user input |
| Termination | Exhausts iterable or hits break | Condition turns False or break |
Common Pitfalls
- Mistake: Expecting range(1, 10) to include 10. Avoid: Set the stop argument to 11 because upper bounds are exclusive.
- Mistake: Manually updating counter variables inside a for loop. Avoid: Let the for loop manage iteration over the iterable automatically.
- Mistake: Using while loops for fixed-count traversals. Avoid: Use for loops with range for cleaner fixed-count execution.
FAQs
- Why does range(1, 10) only count up to 9? Python range boundaries are half-open, meaning the starting value is inclusive but the stopping value is exclusive.
- What names can be used for the loop counter variable? You can use any valid variable name, such as x, i, or counter.
- What is the key difference between continue and break? The continue keyword skips only the remaining code in the current iteration, whereas break terminates the loop entirely.