Skip to main content

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

Easy as ABC!

Easy as ABC!

Say you want to print the numbers 1 to 3. Easy:

print(1)
print(2)
print(3)

Now print 1 to 1000. Still want to type it all out? Yeah, me neither.

Computers are amazing at doing the same thing over and over without getting bored. That's what loops are for.

while

A while loop is like an if that keeps going. While the question is True, Python runs the indented lines, then goes back up and asks again.

count = 1

while count <= 3:
    print(count)
    count = count + 1

print("Done!")
1
2
3
Done!
  1. Is count <= 3? It's 1, so yes. Print 1, then count becomes 2.
  2. Back to the top. Is 2 <= 3? Yes. Print 2, count becomes 3.
  3. Is 3 <= 3? Yes. Print 3, count becomes 4.
  4. Is 4 <= 3? Nope! Skip the loop, print Done!

count = count + 1 looks weird if you think of = as math. But remember, = stores. It works out count + 1 first, then stores the answer back into count. You'll also see it written as count += 1, which means the exact same thing.

Here's the same loop, with one line missing. Run it and watch the console.

Run it and watch what happens.

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.

1, 1, 1, 1, 1, 1...

That's an infinite loop. count never changes, so count <= 3 is True forever, and Python would happily keep printing 1 until the end of time. The editor noticed all that printing and stopped it for you.

Every while loop needs something inside it that eventually makes the question False. Otherwise it never ends.

It happens to everyone. If your program seems frozen, there's a good chance it's stuck in a loop. Press Stop in the editor (or Ctrl + C in a real terminal) and check what's supposed to change.

Alex set the website to self-destruct.

Use a while loop to count down from 5 to 1, then print Bye bye, website. at the end:

5
4
3
2
1
Bye bye, website.

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.