When the number of repetitions is clear, a for loop is often easier to read than a while loop. It expresses “take values from a sequence one by one” in a single line.
range()
range() generates integer sequences and is commonly used with for.
for i in range(5):
print(i, end=' ')
print()
for i in range(10, 15):
print(i, end=' ')
print()
for i in range(1, 10, 2):
print(i, end=' ')Output:
0 1 2 3 4
10 11 12 13 14
1 3 5 7 9range(start, stop, step) starts at start, increases by step, and stops before stop.
KNOWLEDGE QUIZ
Fixed-count accumulation
To sum integers from 1 to 100, use range(1, 101). Since range excludes the stop value, the stop value must be 101.
total = 0
for i in range(1, 101):
total += i
print("Sum =", total)Output:
Sum = 5050This version makes the value range of i easier to see than an equivalent while loop.
Step through an accumulating for loop
Run one statement at a time and watch i flow into total.
01total = 002for i in range(1, 101):03 total += i04print(total)
>>>
KNOWLEDGE QUIZ
Fibonacci sequence
The first two Fibonacci numbers are 1, 1. Starting from the third term, each term equals the sum of the previous two terms.
n = int(input("Enter the number of terms: "))
if n <= 0:
print("Please enter a positive integer.")
elif n == 1:
print(1)
else:
first = 1
second = 1
print(first, second, end=' ')
for i in range(3, n + 1):
current = first + second
print(current, end=' ')
first = second
second = current
print()One possible run:
Enter the number of terms: 10
1 1 2 3 5 8 13 21 34 55The most important updates are:
first = second
second = currentThey slide the two-number window forward, so the next loop can keep using the previous two terms.
Slide the Fibonacci window
Each click executes the next assignment. Notice that assignment order matters.
01first = 1; second = 102for i in range(3, 11):03 current = first + second04 first = second05 second = current
KNOWLEDGE QUIZ
List the leap years in a range
Read a start year and end year, then use for and range to find all leap years.
- Read start_year and end_year.
- Iterate across the interval and test each year for leap-year rules.
- Print all leap years on one line.