3.2 for Loops and range()
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.
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.
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.