for Loops and range()
Learn how for loops repeat code, how range() generates integer sequences, and how to trace each iteration.
In this lesson, you will learn
- ✓Explain how a for loop processes items one at a time.
- ✓Use range() with one, two, and three arguments.
- ✓Explain why the stop value of range() is excluded.
- ✓Trace loop variables and predict exact program output.
- ✓Use for loops to calculate totals and solve simple counting problems.
- ✓Recognize common loop mistakes, including incorrect indentation and range() boundaries.
1. What Is a for Loop?
A loop is a programming construct that repeats instructions. A for loop executes its body once for each item obtained from an iterable. An iterable is an object that can provide its items one at a time, such as a list, a string, or a range.
The loop variable receives the current item on each iteration. Python then executes the indented loop body. When the body finishes, Python moves to the next item. When there are no items left, the loop ends and execution continues with the first statement after the loop.
The general syntax is:
for variable in iterable:
# Statements to repeat
The colon ends the loop header, and indentation identifies the loop body. In Python, the indented statements belong to the loop. A loop variable is not a special keyword; it is a normal variable name chosen by the programmer.
Repeat an operation for each item
Python gets the first item, "apple", assigns it to fruit, and executes print(fruit). On the next iteration, fruit refers to "banana". On the third iteration, it refers to "mango". After all three items have been processed, the loop ends. print() displays each item on a separate line because each call ends with a newline by default.
2. Using range() with One Argument
The built-in range() function represents a sequence of integers. It is commonly used with for loops when you need to repeat an operation a certain number of times.
When range() receives one argument, range(stop), it starts at 0 and generates integers up to, but not including, stop. Therefore, range(4) represents the integers 0, 1, 2, and 3.
The stop value is excluded. This is an important rule: range(4) contains four integers, not five. If stop is zero or negative, range(stop) produces no integers because the default step is positive and the starting value is 0.
Print numbers from 0 to 3
range(4) represents 0, 1, 2, and 3. The loop body executes four times, with number receiving one integer per iteration. The integer 4 is not included because range() excludes its stop value.
Note
3. Using range() with Start and Stop
You can pass two arguments to range(): range(start, stop). The sequence begins at start and proceeds toward stop using the default step of 1. The stop value is still excluded.
For example, range(2, 6) represents 2, 3, 4, and 5. It does not include 6.
The number of integers in range(start, stop), when start is less than or equal to stop and the default step is 1, is stop - start. If start is equal to stop, or start is greater than stop, the range is empty.
Print numbers from 2 to 5
The first argument, 2, is the starting value. The second argument, 6, is the excluded stopping value. Python assigns 2, 3, 4, and 5 to number in successive iterations. The loop ends before number can receive 6.
4. Using range() with a Step
The three-argument form is range(start, stop, step). The step determines how much the sequence changes between consecutive integers.
With a positive step, the sequence moves upward. With a negative step, it moves downward. The step cannot be zero; range() raises ValueError if you supply a step of 0.
For a positive step, the sequence stops before reaching or passing the stop boundary. For a negative step, it stops before reaching or passing the lower stop boundary. Choose the direction of the step to match the direction from start toward stop.
Print even numbers from 2 to 10
The starting value is 2, the stop value is 11, and the step is 2. Each iteration increases number by 2. The sequence is 2, 4, 6, 8, and 10. The stop value 11 is excluded, but 10 is included because it is reached before the boundary.
Note
5. Trace a for Loop Step by Step
A dry run means manually tracing a program to understand what happens at each step. For a for loop, record the current loop variable, any important variable changes, and any output produced during each iteration.
Consider a loop that adds the integers from 1 through 3. The total variable stores the running sum. The statement total += number is equivalent to total = total + number.
The loop body executes once for each value produced by range(1, 4). The final print(total) is outside the loop, so it executes only after all iterations have finished.
Calculate a running total
Before the loop starts, total is 0. During the first iteration, number is 1 and total becomes 0 + 1 = 1. During the second iteration, number is 2 and total becomes 1 + 2 = 3. During the third iteration, number is 3 and total becomes 3 + 3 = 6. After the loop, the final print() displays the completed total of 6. In print(), multiple arguments are separated by a space by default. That is why the labels and values appear with spaces in the output.
Note
6. Practical Applications and Edge Cases
For loops are useful for counting, processing collections, calculating totals, and repeating a fixed number of operations. Choose the loop based on the items you need to process, rather than using range() automatically for every task.
An empty range causes the loop body to execute zero times. This can happen when start equals stop or when the step moves in the wrong direction. An empty range is valid and does not cause an error by itself.
The stop boundary is a frequent source of mistakes. If you need to include the integer 5 while counting upward by one from 1, use range(1, 6), not range(1, 5).
A for loop does not require the loop variable to be named i. Use a meaningful name such as number, score, or fruit when it makes the code easier to understand. Use i or j when a short index-style name is appropriate.
The built-in range() returns a range object, not a list. It represents the integer sequence without creating a list containing every value. You can convert it to a list with list(range(...)) when you specifically need a list.
Handle an empty range
range(3, 3) is empty because its start and stop values are equal. The loop body never executes, so no number is printed. Python continues with the statement after the loop and prints Loop finished.
Caution
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Expecting range(5) to produce 1, 2, 3, 4, 5.
Why it happens: range(stop) starts at 0 and excludes stop, so range(5) yields 0 through 4.
Key takeaway: range(5) produces 0, 1, 2, 3, 4. The one-argument form starts at 0 and excludes the stop value. Use range(1, 6) to produce 1 through 5.
#2 Forgetting the colon at the end of the for statement.
Why it happens: A for statement requires a colon before its indented loop body.
Key takeaway: Write a colon after the loop header, as in for number in range(3):.
#3 Incorrectly indenting the loop body.
Why it happens: The loop body must be indented to show which statements repeat on each iteration.
Key takeaway: Indent the statements that must repeat under the for statement. Statements outside that indentation run after the loop.
#4 Using a positive step when counting downward.
Why it happens: A negative step is needed for a descending range; a positive step moves upward and may produce no values when start is greater than or equal to stop.
Key takeaway: Use a negative step, such as range(5, 0, -1), to count from 5 down to 1.
#5 Using zero as the step.
Why it happens: A step of zero cannot advance a range and Python raises ValueError.
Key takeaway: Use a nonzero step. A zero step causes range() to raise ValueError.
#6 Thinking the loop variable automatically resets to its original value inside every iteration.
Why it happens: The loop variable is assigned the next item on each iteration, so its value changes as the loop progresses.
Key takeaway: The loop variable is assigned the next item on each iteration. If you change it inside the body, Python will assign the next item when the next iteration begins.
#7 Putting a final calculation or summary print inside the loop when it should run only once.
Why it happens: Statements placed inside the loop execute on every iteration; put final totals or summary output after the loop when they should happen once.
Key takeaway: Check the indentation. Place statements after the loop at the outer indentation level if they should execute once after all iterations.
#8 Assuming range() creates a list.
Why it happens: range() represents an integer sequence efficiently and is not itself a list; use list(range(...)) when a list is explicitly needed.
Key takeaway: range() returns a range object representing an integer sequence. Use list(range(...)) if a list is required.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is a for loop in Python?
Q2:What is range() used for?
Q3:Why does range() exclude the stop value?
Q4:What is the difference between range(5) and range(1, 5)?
Q5:How do you count backward with range()?
Q6:What happens if the range is empty?
Q7:What is the difference between range() and list(range())?
Key takeaways
- A for loop executes its body once for each item provided by an iterable.
- range(stop) starts at 0 and excludes stop.
- range(start, stop) lets you choose the starting value while still excluding stop.
- range(start, stop, step) controls the starting value, stopping boundary, and direction or increment.
- A positive step counts upward; a negative step counts downward; a zero step raises ValueError.
- The loop body must be indented correctly, and statements outside the loop run after iteration finishes.
- A dry run helps track the loop variable, running totals, and exact output.
- Test boundary cases, including empty ranges, and verify the expected output.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: