for Loops & range()
When you know how many times to repeat, for is your go-to. Paired with range(), it gives you precise control over counting.
for loops with range()range(start, stop, step)for vs whileThe for Loop
A for loop iterates over a sequence. The simplest way to create a sequence of numbers is range():
range(5) generates numbers 0 through 4 β that's 5 numbers, starting at 0. The variable i takes each value in turn.
The Three Forms of range()
| Form | Produces | Use When |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | You just need N repetitions |
| range(1, 6) | 1, 2, 3, 4, 5 | You need a specific start and end |
| range(0, 10, 2) | 0, 2, 4, 6, 8 | You need to skip/step by N |
| range(10, 0, -1) | 10, 9, 8, β¦, 1 | You need to count backwards |
range(start, stop) includes start but excludes stop. So range(1, 6) gives you 1β5, not 1β6. This is consistent throughout Python!
for vs while
Use for when you know how many iterations you need (or you're iterating over a sequence). Use while when you're waiting for a condition to change and don't know how many iterations it'll take.
range(1, 11) not range(1, 10). The stop value is always excluded.
Challenges
Challenge 1: Times Table
Print a multiplication table for a given number.
Use an f-string: f"{num} x {i} = {num * i}"
for i in range(1, 11): gives you 1 through 10.Hint 2: Inside:
print(f"{num} x {i} = {num * i}")Challenge 2: Sum of N
Calculate the sum of integers from 1 to N using a for loop.
Example: n=5 β 1+2+3+4+5 = 15
for i in range(1, n + 1): β remember, range excludes the stop value!Hint 2: Inside:
total += iHint 3: Fun fact: the answer for n=100 is 5050 (Gauss figured this out as a kid!).
Challenge 3: Staircase
Print a right-aligned staircase of # symbols.
Example (height=5):
#
##
###
####
#####
Hint: On row i (starting from 1), there are (height - i) spaces and i hashes.
for i in range(1, height + 1): β i goes from 1 to height.Hint 2: Each line = spaces + hashes. Spaces =
" " * (height - i), hashes = "#" * iHint 3:
print(" " * (height - i) + "#" * i)Challenge 4: FizzBuzz
The classic programming challenge! Print numbers 1 to n, but replace multiples of 3 with "Fizz", multiples of 5 with "Buzz", and multiples of both with "FizzBuzz".
β’ Divisible by 3 AND 5 β print "FizzBuzz"
β’ Divisible by 3 only β print "Fizz"
β’ Divisible by 5 only β print "Buzz"
β’ Otherwise β print the number
Example: 1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16...
Hint 2:
if i % 3 == 0 and i % 5 == 0: β "FizzBuzz", elif i % 3 == 0: β "Fizz", etc.Hint 3: Alternative:
if i % 15 == 0: (since 15 = 3 Γ 5)