Course outline · 0% complete

0/32 lessons0%

Course overview →

for and range

lesson 5-1 · ~11 min · 13/32

Quiz

Warm-up from lesson 2-1: in the string `s = "loop"`, what is `s[0]`?

for: do something for each item

Loops are the reason computers beat hand work. Check 10,000 rows, resize every photo in a folder, send a message to every subscriber: each is a few lines repeated automatically. From here on, nearly every useful program you write in this course, and on the job, has a loop in the middle.

A for loop runs its indented body once per item in a sequence. A string is a sequence, so this visits every character:

for ch in "abc":
    print(ch)

ch is the loop variable: Python assigns it the next character before each pass through the body.

range: a sequence of numbers on demand

When you want to repeat something N times or count, use range():

  • range(5) produces 0, 1, 2, 3, 4 (starts at 0, stops before 5)
  • range(2, 6) produces 2, 3, 4, 5
  • range(0, 10, 2) produces 0, 2, 4, 6, 8 (the third number is the step)

The stop value is excluded, exactly like string slices in lesson 2-1. range(5) has 5 items, which makes repeat 5 times read naturally.

Code exercise · python

Run this. Count how many times each body executes and match it to the range rules above.

next item left?run the bodygo back and check againno items left: leave the loop
One loop iteration: take the next item, run the body, come back, check again. The gold dot traces the cycle.

Code exercise · python

Your turn. Print the 5 times table from 1 to 5, one line each, formatted exactly like `5 x 1 = 5` (use an f-string inside the loop).

Code exercise · python

One more range trick you will need: a negative step counts DOWN. range(10, 0, -2) starts at 10, steps by -2, and stops before reaching 0. Run it and check the last value printed.