Loops are the programming construct that turns 'do one thing' into 'do many things without copying the code.' In Python, the two primary loop statements are for and while. A for loop walks across any iterable — a list, tuple, string, dictionary, file object, generator, or custom class that implements __iter__ — and binds each element to a name. A while loop keeps running as long as a Boolean condition evaluates to True and is the right choice when the number of iterations is not known in advance (polling, retrying, waiting for user input).
Every loop needs a clear plan for when it stops. for loops stop automatically when the iterable is exhausted; while loops stop when the condition becomes false or when a break statement runs. The continue keyword skips the remainder of the current iteration and moves to the next one, which is useful for filtering out unwanted values without adding extra indentation.
Python loops also come with a few efficiency helpers: range() produces a lazy integer sequence for counted iteration, enumerate() adds an index while iterating, and zip() walks multiple sequences in parallel. For simple transformations, list comprehensions ([expr for x in items if cond]) and generator expressions ((expr for x in items)) express a loop in a single readable line and often run faster than the equivalent manual loop.
Think of a loop as three things bundled together: an iterable (the source of items), a binding name (what each item is called inside the block), and a body (what you do with that name). When you understand those three pieces, most real-world iteration patterns in Introduction to Loops become variations of the same idea.
These are the core Python tools used in Introduction to Loops. Skim the table before reading the code example, and click any name to open the official documentation.
| Tool | Purpose |
|---|---|
forkeyword | Walks through every item of a sequence one at a time. |
whilekeyword | Repeats a block as long as a condition stays True. |
breakkeyword | Exits the nearest loop immediately. |
continuekeyword | Skips to the next loop iteration. |
range()built-in function | Produces a lazy sequence of integers for counted loops. |
enumerate()built-in function | Pairs items with their index during iteration. |
zip()built-in function | Iterates two or more sequences in parallel. |
list comprehensionexpression | Builds a new list by looping and filtering in one line. |
Introduction to Loops Code example
Use loops with validation and reusable logic for Introduction to Loops.
# Lesson: Introduction to Loops
# Goal: iterate a list, validate input, transform every item, then report results.
# The surrounding code (imports, constants, helper, usage) is intentionally shown
# so you can see how a realistic loop fits inside a small script.
from statistics import mean
DEFAULT_FACTOR = 3 # multiplier used when the caller doesn't pass a value
def scale_values(values: list[int], factor: int) -> list[int]:
'''Return a new list where every item has been multiplied by `factor`.'''
if factor <= 0:
raise ValueError("factor must be positive")
return [value * factor for value in values]
def describe(label: str, values: list[int]) -> None:
'''Small helper so the main script stays readable.'''
print(f"{label} count={len(values)} avg={mean(values):.2f} values={values}")
# --- main script ---------------------------------------------------------
numbers = [2, 4, 6, 8]
describe("input", numbers)
scaled = scale_values(numbers, factor=DEFAULT_FACTOR)
print("original:", numbers)
print("introduction_to_loops_loop_result:", scaled)
# follow-up use: feed the transformed list into another loop
running_total = 0
for index, value in enumerate(scaled, start=1):
running_total += value
print(f"step {index} -> total={running_total}")
Walk through each part before moving to the next lesson:
1) `scale_values()` isolates loop logic so you can reuse it.
2) Input validation (`factor <= 0`) prevents silent bad math.
3) The list comprehension processes each value predictably.
4) Final prints compare original and transformed data.Try both examples below to strengthen understanding.
# Example A: filter then transform
values_introduction_to_loops = [1, 2, 3, 4, 5, 21]
even_scaled_introduction_to_loops = [v * (8 + 2) for v in values_introduction_to_loops if v % 2 == 0]
print(even_scaled_introduction_to_loops)
# Example B: accumulate with running total
running_introduction_to_loops = 0
for v in values_introduction_to_loops:
running_introduction_to_loops += v
print("running_total_introduction_to_loops:", running_introduction_to_loops)
Run these assertions after the example. If nothing prints, tests passed.
assert scale_values([1, 2], 2) == [2, 4]
try:
scale_values([1], 0)
except ValueError:
pass
else:
raise AssertionError("Expected ValueError for non-positive factor")
Your exact values can vary slightly (especially dates/times), but the structure should match.
original: [2, 4, 6, 8]
introduction_to_loops_loop_result: [6, 12, 18, 24]