▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
for loops and range()
Repeat work a set number of times.
🎬 Video version coming soon — read it now
A loop repeats code so you don't have to copy and paste it. The for loop repeats once for each item in a sequence.
Looping over a range of numbers
This prints Hello 0 through Hello 4. range(5) gives 0, 1, 2, 3, 4: five numbers, starting at 0 and stopping before 5.
Other ways to use range
Example: a multiplication table
Looping over a string
A for loop works on any sequence, including text:
Adding things up
A very common pattern is to start a total at 0 and add to it inside the loop:
Notice that total = 0 sits before the loop. Put it inside and it resets every time.
_: for _ in range(3): print("Hip hip hooray!").In one line
A for loop runs once per item; range(start, stop, step) makes number sequences that stop before stop.
Share with a friend