Skip to content
IT Vizag
← Decisions & Loops

▶ 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()

Lesson 4 of 9 · 1 min read

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

🔒 Code example: sign up free (above) to unlock it.

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

🔒 Code example: sign up free (above) to unlock it.

Example: a multiplication table

🔒 Code example: sign up free (above) to unlock it.

Looping over a string

A for loop works on any sequence, including text:

🔒 Code example: sign up free (above) to unlock it.

Adding things up

A very common pattern is to start a total at 0 and add to it inside the loop:

🔒 Code example: sign up free (above) to unlock it.

Notice that total = 0 sits before the loop. Put it inside and it resets every time.

Tip: If you don't need the loop variable, name it _: 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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend