Lesson · Python for Beginners
Loops with for and while
Loops reduce repetition, but their stopping rule must be clear.
What you will learn
- Loop over a range
- Choose between for and while
- Avoid an unintended infinite loop
Repeat over known items
A for loop takes each item from an iterable in turn and runs an indented body for it. range(1, 4) produces 1, 2, and 3; the ending number is excluded. This predictable behavior is useful when the number of repetitions is known or when a collection already contains the items to process.
Repeat while a condition holds
A while loop checks its condition before each pass. Something in the loop usually needs to move the program toward making that condition false. If nothing changes, the loop may run forever. Start with a small test value and confirm the update and stopping condition before using larger input.
Use the loop variable clearly
The name after for refers to the current item. It changes each time the loop moves to the next item, so avoid modifying a collection while iterating over it unless you understand the consequences. A descriptive variable name makes the body easier to read than a single letter when the item has meaning.
Choose the simpler loop
Prefer for when processing each item or repeating a known count. Prefer while when the decision to continue depends on a condition that changes during execution, such as waiting for a valid choice. The example uses for because its three values are known in advance.
Trace one pass at a time
For a loop that updates a total, make a small table with the current item and total before and after the pass. This exposes whether each item is counted once and whether the initial value is appropriate. For a while loop, add the condition to the table too; its change should make the stopping point apparent.
total = 0
for number in range(1, 4):
total += number
print(total)
Expected output
6
Practice exercise
Use a for loop to print the even numbers 2, 4, and 6.
Show a hint
A range can use a step value.
Show one possible solution
for number in range(2, 7, 2): print(number) visits 2, 4, and 6.
Quick check
The start is included and the stop value is excluded.