Loops: Beginner
Waymo's self-driving data pipeline processes raw LiDAR point clouds and camera frames using Python preprocessing scripts that iterate over thousands of sensor readings per second. Waymo engineers have documented how every mile logged by the fleet generates labeled training data that Python loops process to improve the perception models continuously. The for loops and while loops you are about to write are the same iteration constructs powering that kind of large-scale sensor data processing.
Iterating with for Loops
Loop through any list or string
Maria Santos filed a sprint blocker at 8:47 AM. Her intern wrote a four-line script. One print statement in the code, three lines on the console. Alex Park reviewed the code and signed off. Now Maria wants answers before the stakeholder review.
One list. Three names. One variable that keeps changing.
| variable | value |
|---|---|
| names | ['Alice', 'Bob', 'Charlie'] |
| name | (changes each iteration) |
| iteration | name value | output |
|---|---|---|
| 1 | Alice | Welcome, Alice |
| 2 | Bob | Welcome, Bob |
| 3 | Charlie | Welcome, Charlie |
The for loop iterates over each item in a sequence (like a list, string, or tuple) one at a time. On each iteration, the loop variable is assigned the next item from the sequence, and the loop body executes with that value.
Basic for Loop Syntax
A for loop has the form: for variable in sequence: followed by an indented block. The variable takes on each value from the sequence in order:
The loop executes three times. On the first iteration, fruit is "apple". On the second, it is "banana". On the third, "cherry". After all items are processed, the loop ends and execution continues with the next unindented statement.
Looping Over Strings
Accumulating Results
sum() and len() are built-in, understanding the accumulator pattern is essential. Many real-world calculations require custom accumulation logic that built-in functions cannot handle.Building New Lists
> A loop adds up numbers using an accumulator variable. Pick the operator to see how the running total changes.
total = 0 for n in [1, 2, 3]: total n print(total)
Looping Multiple Data Types
Finding Values in Lists
max(), min(), and list comprehensions that can do these tasks more concisely, understanding the loop-based approach is essential for more complex searches that built-ins cannot handle.range() Function
Generate number sequences with range()
The range() function generates a sequence of numbers. It is commonly used with for loops when you need to repeat an action a specific number of times or iterate over a sequence of integers.
range() with One Argument
range(n) generates numbers from 0 up to (but not including) n. This gives you exactly n iterations:
Notice that range(5) produces 0, 1, 2, 3, 4 - five numbers starting from 0, not including 5. This is consistent with zero-based indexing.
range() with Two Arguments
range(start, stop) generates numbers from start up to (but not including) stop:
range() with Three Args
range(start, stop, step) lets you specify the increment between numbers:
Each form of range() gives you a different level of control over the generated sequence. Here are the three signatures and their behavior at a glance:
range() for Index Access
Sometimes you need both the index and the value. You can use range with len to loop by index:
Using range(len(list)) for index access works, but Python has a better way: enumerate(). You will learn this in the intermediate lesson. For now, range(len()) is fine.
Sequences from range()
The range function is not limited to controlling loops. You can convert a range to a list to create numeric sequences for various purposes:
The list() function converts the range object into an actual list. This is useful when you need to store the sequence or pass it to a function that requires a list rather than an iterator.
Repeating Actions N Times
> Generate a sequence of integers starting at 2 and stopping before 8. Pick the built-in that produces the number sequence, and the one that counts how many numbers were generated.
nums = list((2, 8)) print(nums[0]) print((nums))
range() is memory efficient: it does not store all the numbers at once. It generates each value on demand, making it safe to use with very large ranges like range(1_000_000) without consuming extra memory.
The three-argument form range(start, stop, step) covers almost every numeric sequence you will need in a for loop, including counting up, counting down, and selecting every nth value.
When you need the actual list of numbers for slicing, indexing, or repeated access, wrap range() in list(). Otherwise, iterating over the range object directly in a for loop is the preferred approach.
Loops with while
Repeat actions until a condition fails
A while loop repeats as long as its condition is True. Unlike for loops that iterate a fixed number of times, while loops continue until the condition becomes False. This makes them ideal when you do not know in advance how many iterations you need.
Basic while Syntax
A while loop has the form: while condition: followed by an indented block. The condition is checked before each iteration:
Comparing while and for
- Iterating over a sequence
- You know how many times to loop
- Processing each item in a collection
- Using range() for a count
- Unknown number of iterations
- Waiting for a condition
- User input loops
- Reading until end of data
- Processing every item in a list, string, or file: use a
forloop. - Repeating an action a known number of times: use
forwithrange(). - Waiting for user input or an external condition: use a
whileloop. - Polling or retrying until success or timeout: use
whilewith a counter.
Common while Patterns
Avoiding Infinite Loops
> This while loop should print 0 through 4, but it runs forever. Find the tile that prevents the counter from advancing.
LogicError: count never changes, loop runs forever
Infinite Loops: while True
A common pattern is to use while True combined with break to create loops that exit based on complex conditions. This is especially useful when the exit condition is checked in the middle of the loop body rather than at the beginning:
while True pattern gives you full control over exactly when the loop exits. Just make sure every possible code path eventually reaches a break statement, or includes logic to prevent infinite execution.Simulating Do-While Loops
Using break and continue
Exit or skip iterations on demand
Python provides two statements to control loop execution: break exits the loop immediately, and continue skips the rest of the current iteration and moves to the next one.
The break Statement
break immediately terminates the innermost loop. Execution continues with the first statement after the loop:
When the loop finds -2, break executes and the loop ends immediately. The remaining items (7, 8) are never checked.
The continue Statement
continue skips the rest of the current iteration and jumps to the next iteration of the loop:
When continue executes, the loop immediately moves to the next item. The print statement after continue is skipped for negative numbers.
break vs continue
- Exits the loop entirely
- Loop body never runs again
- Continues after the loop
- Use for early termination
- Skips current iteration only
- Loop continues with next item
- Loop may run many more times
- Use to skip certain items
break and continue in while
while loops, make sure to update the loop variable before continue, or you may create an infinite loop. The continue skips everything after it, including the increment.Combining break with Flags
Nested Loops and break
The break statement only exits the innermost loop. If you have nested loops and want to exit the outer loop, you need additional logic like a flag variable:
Knowing when to use break versus continue prevents subtle bugs and keeps loop logic readable. Follow these guidelines:
- Use break for early exit on first match
- Use continue to skip invalid items
- Update counter before continue in while
- Use flags to exit outer loops
- Use break when you need all matches
- Nest continue inside complex conditions
- Forget counter update causes infinite loop
- Assume break exits all nested loops
> Collect the first 3 odd numbers from a range. Pick the keyword that skips even numbers, and the one that stops the loop once 3 odds are found.
result = [] for n in range(10): if n % 2 == 0: result.append(n) if len(result) == 3: print(result)
break and continue are most valuable when processing input that has mixed valid and invalid entries. Use continue to skip bad records and break to stop as soon as a target is found.
A common pattern in searching is to use break when a match is found and rely on a flag variable or else clause to detect when no match was found after the full loop completes.
In while loops, forgetting to update the loop counter before a continue statement is a frequent cause of infinite loops. Always ensure the condition can eventually become False regardless of which path through the loop body is taken.
Loop Variable Scope
Predict variable values after loops end
In Python, loop variables (the variable after for or used in a while condition) remain accessible after the loop ends. This is different from some other languages where loop variables are scoped only to the loop body.
Loop Variables Persist
After a for loop completes, the loop variable retains its last value:
After the loop, i holds the last value it was assigned, which is 4 (the last number in range(5)). For letters, it holds "C".
Empty Loops: Undefined Vars
Nested Loop Scope
Common Mistakes
> You are a data analyst at The Washington Post writing a Python script to iterate through a batch of 50 daily report files, extract the key engagement metric from each, and print a summary line for every file processed.
for loop iterates through each file in the batch list so no file is skipped or manually tracked.while loop continues processing until a stop condition like reaching the end of records or hitting a file error is met.for loops iterate over each item in a sequence (list, string, tuple)range(n) generates 0 to n-1; range(start, stop, step) for full controlwhile loops repeat while condition is True; ensure the condition eventually becomes Falsebreak exits the loop immediately; continue skips to the next iterationLoops: Beginner
Repeating actions efficiently
- Category
- Python
- Difficulty
- beginner
- Duration
- 39 minutes
- Challenges
- 0 hands-on challenges
Topics covered: Iterating with for Loops, range() Function, Loops with while, Using break and continue, Loop Variable Scope
Lesson Sections
- Iterating with for Loops (concepts: pyForBasic)
A for loop repeats a block of code once for each item in a sequence. Without one, processing fifty files means writing fifty nearly-identical blocks of code. A loop collapses all of that into three lines. Basic for Loop Syntax Looping Over Strings Strings are sequences of characters, so you can loop over them character by character: Each character in the string becomes the loop variable in turn. This is useful for analyzing text character by character. Accumulating Results A common pattern is to
- range() Function
range() with One Argument range() with Two Arguments range() with Three Args range() for Index Access Sequences from range() Repeating Actions N Times Sometimes you just need to repeat an action a specific number of times without caring about the loop variable. By convention, you can use an underscore for variables you do not intend to use:
- Loops with while (concepts: pyWhileLoops)
Basic while Syntax The loop checks the condition, executes the body if True, then checks again. When count reaches 5, the condition becomes False and the loop ends. Here is the execution model step by step: Comparing while and for Choose the right loop type based on your situation: When deciding which loop type to use, keep these practical rules in mind. They cover the most common scenarios you will encounter in real code. Common while Patterns Here are typical use cases for while loops: Avoidin
- Using break and continue (concepts: pyBreakContinue)
The break Statement The continue Statement break vs continue Understanding the difference is crucial: break and continue in while These statements work the same way in while loops: Combining break with Flags Sometimes you need to know whether a loop exited normally or via break. A flag variable can track this distinction: The flag variable starts False and becomes True only if the target is found. After the loop, you check the flag to determine the outcome. This pattern is useful when you need d
- Loop Variable Scope
Loop Variables Persist Empty Loops: Undefined Vars If a loop never executes (empty sequence), the loop variable is never assigned: Understanding how loop variables behave in Python helps avoid common bugs, especially when accessing them after the loop ends: Nested Loop Scope Each loop has its own variable, but inner loops can access outer loop variables: Common Mistakes These are frequent errors when writing loops: Loops are essential for automating repetitive tasks and processing collections of