Loops: Beginner
The for loop names a variable, then a sequence. for fruit in fruits: reads as "for each fruit in fruits". On every pass, Python assigns the next item to fruit and runs the indented lines under the colon. When the sequence runs out, the loop is over.
A list is a sequence of values written between square brackets and separated by commas, such as ["apple", "banana", "cherry"]. It keeps its items in the order they were written, and a loop visits them in that order: first item first, last item last.
1fruits = ["apple", "banana", "cherry"]23for fruit in fruits:4 print("I like", fruit)56print("Done!")
The loop body is 1 line, and it runs 3 times. On the first pass fruit holds "apple", on the second "banana", on the third "cherry". After the third pass there is no fourth item, so Python moves to the first line at the loop's own indentation. "Done!" prints once, after the 3 greetings, because it sits outside the body.
| Pass | fruit holds | Line printed |
|---|---|---|
| 1 | "apple" | I like apple |
| 2 | "banana" | I like banana |
| 3 | "cherry" | I like cherry |
| after the loop | "cherry" (unchanged) | Done! |
Strings are sequences too
1word = "Python"23for char in word:4 print(char)
Carrying a result across passes
1numbers = [10, 20, 30, 40, 50]23# Calculate the sum4total = 05for num in numbers:6 total = total + num78print("Sum:", total)910count = 011for num in numbers:12 if num > 25:13 count = count + 11415print("Numbers > 25:", count)
| Pass | num | total after the pass |
|---|---|---|
| 1 | 10 | 10 |
| 2 | 20 | 30 |
| 3 | 30 | 60 |
| 4 | 40 | 100 |
| 5 | 50 | 150 |
total = 0 before the loop matters. If that line sat inside the body, total would reset to 0 on every pass and the final answer would be 50, the last number alone. The second loop counts instead of sums: count goes up by 1 only on passes where the if is true, which happens for 30, 40 and 50, so it prints 3.
Practice: counting letters
The print sits inside the loop body. What does this program print?
Writing an accumulator from scratch means filling 3 slots in the right places: the starting value on the line above the for, the list's name after in on the for line, and the loop variable's name inside the body, spelled exactly as the for line spells it. A sum starts from 0, since adding 0 changes nothing.
A for loop needs a sequence to walk. When the sequence you want is a run of numbers, range() builds it for you. range(5) produces 0, 1, 2, 3, 4: it starts at 0, climbs by 1, and stops before 5. The number you pass is the stop, and the stop itself is never produced.
1# Print 0 to 42for i in range(5):3 print(i)
Start, stop and step
range() accepts 1, 2 or 3 numbers. A single number is the stop, and the start defaults to 0. Given 2, range reads them as the start and the stop. A third number is the step: how far each produced number is from the one before it. A negative step counts down.
| Call | Produces | How many |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | 5 |
| range(2, 6) | 2, 3, 4, 5 | 4 |
| range(0, 10, 2) | 0, 2, 4, 6, 8 | 5 |
| range(10, 0, -3) | 10, 7, 4, 1 | 4 |
| range(3, 3) | nothing | 0 |
| range(5, 2) | nothing | 0 |
Repeating something n times
Sometimes the numbers themselves are beside the point and you want the body to run a fixed number of times. range(3) still produces 0, 1 and 2, but the body never reads them. The convention is to name the variable _ to signal to anyone reading the code that nothing uses it.
Getting the stop right
- ▸The start is included and the stop is excluded: range(2, 6) produces 2, 3, 4, 5.
- ▸range(n) produces exactly n numbers, 0 through n - 1, so the body runs n times.
- ▸A step that moves away from the stop, or a start already past the stop, produces nothing and the loop body runs 0 times.
How many lines does this loop print?
Working backwards from a wanted sequence to a range call takes 3 readings. The first value is the start. The gap between neighbours is the step. The stop is any number past the last value and at most 1 step beyond it, and last value + 1 is the safe choice. For 3, 6, 9 that gives range(3, 10, 3).
A countdown reads the same way with a negative step. The start is the first number printed and the step is -1. The excluded stop now sits on the low side, so it goes 1 below the last number you want: to end on 3, stop at 2. range(9, 2, -1) produces 9 down to 3.
A for loop knows how many passes it will make before it starts: 1 per item. A while loop does not. It checks a condition, runs the body if the condition is True, then returns to the condition and checks again. It stops the first time the check comes back False, and the number of passes is whatever that takes.
1count = 023while count < 5:4 print("Count is", count)5 count = count + 167print("Loop finished!")
| Check | count < 5 | Body prints | count after the body |
|---|---|---|---|
| 1 | 0 < 5 is True | Count is 0 | 1 |
| 2 | 1 < 5 is True | Count is 1 | 2 |
| 3 | 2 < 5 is True | Count is 2 | 3 |
| 4 | 3 < 5 is True | Count is 3 | 4 |
| 5 | 4 < 5 is True | Count is 4 | 5 |
| 6 | 5 < 5 is False | nothing, loop ends | 5 |
Setup, condition and progress in a while loop
When the number of passes is unknown
Zero passes
- You have a list or a string to walk through.
- You know the number of passes up front, so range(n) fits.
- Python moves to the next item for you, so there is no progress line to forget.
- The stopping point depends on values computed during the loop.
- You repeat until a target is reached, such as doubling past 100.
- You write the progress line yourself, and the loop runs until your condition fails.
What does this program print?
The comparison on the while line decides the last value the body sees. while n > 0 lets the body run for 1 and stops when n is 0. while n >= 0 also lets 0 through, so the body runs 1 extra time. When a loop prints 1 value too many or too few, test the boundary value against the condition by hand.
A target such as "the first value that is at least X" turns into a condition by asking when the loop should keep going: while the value is still short of X. To find the first multiple of 3 that is at least 20, start from m = 0, loop while m < 20: with m = m + 3 as the progress line, and the loop stops on 21.
Inside a loop body, 2 statements can change the loop's course. break ends the loop at once: the rest of the body is skipped, no more passes happen, and Python moves to the first line after the loop. continue ends only the current pass: the rest of the body is skipped, and the loop moves to the next item, or in a while loop, back to the condition check.
break: stop searching once found
1# Find first negative number2numbers = [1, 5, 3, -2, 7, 8]34for num in numbers:5 if num < 0:6 print("Found negative:", num)7 break8 print("Checked:", num)910print("Search complete")
| num | num < 0 | What happens |
|---|---|---|
| 1 | False | prints Checked: 1 |
| 5 | False | prints Checked: 5 |
| 3 | False | prints Checked: 3 |
| -2 | True | prints Found negative: -2, then break |
| 7, 8 | never tested | loop already ended |
continue: skip this one
1# Print only positive numbers2numbers = [1, -2, 3, -4, 5]34for num in numbers:5 if num < 0:6 continue7 print(num)89print("Done")
- Ends the entire loop.
- No further items are visited.
- Execution continues at the first line after the loop.
- Use it when the answer is found and the rest is wasted work.
- Ends only the current pass.
- The next item is visited as usual.
- Execution jumps to the top of the loop.
- Use it to skip items that fail a test while keeping the loop running.
Did the loop find it?
1# Search with a found flag2numbers = [1, 3, 5, 7, 9, 11]3target = 74found = False56for num in numbers:7 if num == target:8 found = True9 break1011if found:12 print("Found", target, "in the list!")13else:14 print(target, "not found")1516# Same search, target not present17target = 818found = False19for num in numbers:20 if num == target:21 found = True22 break2324if found:25 print("Found", target)26else:27 print(target, "not found")
break inside while
while True: is a loop whose condition never fails on its own, so a break inside it is the only way out. The pattern suits loops where the exit test belongs in the middle of the body, after some work has been done on the pass, rather than at the top.
continue can skip the progress line in while
- Use break the moment a search succeeds, so the remaining items are never visited.
- Pair break with a flag when code after the loop needs to know whether it fired.
- Put the progress line before any continue in a while loop.
- Expect lines after a break inside the body to run; they are skipped on that pass.
- Use continue where wrapping the rest of the body in an if would read better.
- Rely on the loop variable alone to tell you whether a break happened.
The remainder n % 3 is 0 for multiples of 3. What does this loop print?
The order of lines inside the body decides whether the item that triggers break gets processed. When the if holding break comes before the print, the triggering item ends the loop without being printed. When the print comes first, that item is printed and then the loop ends. Either way, the line after the loop runs once.
Swapping continue for break turns a filter into a stop sign. In a loop that sums only positives, continue drops each negative and keeps adding the rest. A break in that spot ends the sum at the first negative, so every positive after it is lost and the total comes out low with no error to warn you.
1for i in range(3):2 print("inside", i)3print("after", i)45total = 06for n in [4, 9, 2]:7 total = total + n8print("last n", n, "total", total)910count = 1011while count < 13:12 count = count + 113print("count", count)
Each loop variable survives its loop and holds the last value assigned to it.
| Loop | Last assignment to the variable | Value after the loop |
|---|---|---|
| for i in range(3) | i = 2 on the third pass | 2 |
| for n in [4, 9, 2] | n = 2 on the third pass | 2 |
| while count < 13 | count = 13 inside the body | 13 |
break leaves the variable on the found item
A loop that never runs
If the sequence is empty, the body runs 0 times and the loop variable is never assigned. Reading it afterwards raises a NameError if no earlier line created it, the same error you get from any variable that was never assigned. If an earlier line did create it, it keeps that earlier value, because the loop never touched it.
Reusing a name
- ▸A for loop variable holds the last item visited: the final item if the loop ran to the end, or the item that triggered break.
- ▸If a while loop ends because its condition fails, the counter holds the first value that made it False; if break ends it, the counter holds what the last pass assigned.
- ▸A loop over an empty sequence never assigns its variable, so the variable is either missing or still holds an earlier value.
- ▸Accumulators like total keep whatever the last pass left in them, and nothing resets them.
What does this program print?
Predicting a for variable after a break means finding the first item, in list order, that passes the if, and stopping there. Later items are never assigned, even ones that would also pass. Over [2, 15, 30] with a break on n > 10, n ends at 15, and 30 never reaches the variable.
When a printed value belongs to the wrong loop, look for a name that 2 loops share. The second loop's assignments land in the same variable, so once it ends, the first loop's value is gone. Giving each loop a variable named for its own data, such as name and score, keeps both values.
> Picture 1 listener's Spotify Wrapped card computed from their play records by a short program. One for loop walks the records and carries a running total of minutes, the way the accumulate example carried its sum. A second loop counts how many records clear a 30-second mark, skipping the rest with continue, because a track skipped after 5 seconds should not count as a play. A while loop keeps pulling the next page of records until a page comes back empty, since nobody knows up front how many pages a heavy listener has. And a search for the first record from a brand-new artist uses break the moment it finds one, with a found flag so the card can say whether that discovery ever happened.
Make Python repeat itself: walk lists and strings, count with range, loop while a condition holds, and exit on demand.
- Category
- Python
- Difficulty
- beginner
- Duration
- 39 minutes
- Challenges
- 24 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: Iteration)
A loop runs the same block of code once for every item in a sequence. Greeting 3 friends takes 3 print statements. Greeting 3,000 customers takes a loop, and the loop is the same 2 lines either way, because the number of passes comes from the data and the code stays fixed. Strings are sequences too A string is a sequence of characters, so a for loop over a string hands you 1 character per pass. "Python" has 6 characters, so the body below runs 6 times and prints 6 lines of 1 letter each. The loo
- range() Function (concepts: Iteration)
The loop makes 5 passes, one per number, and the last printed value is 4. This lines up with how positions are counted in Python: the first position is 0, so the 5 positions of a 5-item sequence are 0 through 4, and range(5) produces exactly those 5 numbers. Start, stop and step The stop stays excluded in every form. range(2, 6) ends at 5. range(10, 0, -3) keeps producing values while they are above 0, so 1 is the last one and -2 is never reached. range(5, 2) uses the default step of 1 and can't
- Loops with while (concepts: Conditional Loops)
The check runs 6 times and the body runs 5 times. On the sixth check count is 5, 5 < 5 is False, and Python jumps to the line after the loop. A while loop that ends because its condition fails has this shape: the condition is tested 1 more time than the body runs, and the final test is the one that fails. A break statement can end a loop before its condition ever fails. Setup, condition and progress in a while loop The progress line is the one that gets dropped. Without count = count + 1, count
- Using break and continue (concepts: Loop Control)
break: stop searching once found The list has 6 numbers, and only 4 passes run. The first 3 passes fail the if, print "Checked:", and move on. On the fourth pass -2 passes the if, "Found negative: -2" prints, and break ends the loop before the "Checked:" line runs and before 7 and 8 are ever visited. "Search complete" prints because it sits after the loop at the outer indentation, and break only skips what's inside the loop. continue: skip this one All 5 passes happen here. On the passes for -2
- Loop Variable Scope (concepts: Iteration)
A loop variable in Python is an ordinary variable. The for loop assigns to it on every pass, and the loop ending does not delete it or reset it. Whatever value it was given last is still there, and code after the loop can read it. This is useful, and it is also a source of surprises when you expect the variable to vanish. The first loop's last assignment was i = 2, so "after 2" prints. The second loop's last item was 2, so n is 2 while total holds the full sum of 15. The while loop reads differe