Skip to main content

Unit 4 · Loop-de-Loop · Lesson 35 of 57

For What It's Worth

for loops

while loops are great when you don't know how many times you'll go around (like a login: who knows how many tries it'll take?).

But a lot of the time, you do know. "Do this 10 times." For that, there's the for loop:

for number in range(5):
    print(number)

range(5) hands the loop a bunch of numbers, one at a time. Each time around, the next one gets stored in number, and the indented code runs.

No count = count + 1, no infinite loops. The for loop handles all of that for you.

Quick, before you run it: what's the last number you think it'll print?

Run it and look closely at the first and last numbers.

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Question

Answer it in the lesson and it is checked as soon as you send it. Create a free account to do this part.

Picking where to start

If you want to start somewhere other than 0, give range two numbers: where to start, and where to stop.

for number in range(1, 6):
    print(number)
1
2
3
4
5

The stop number never gets included. range(1, 6) stops right before 6. It's a little weird, but you'll get used to it.

Rishabh has a math test tomorrow, and he needs the 7 times table.

Use a for loop and an f-string to print:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21

...all the way up to 7 x 10 = 70.

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.