Skip to content

Loops: for and while

Programming Python Difficulty 1/5

Beginning of the lesson

Loops: for and while

How to make Python repeat work for you

Big Idea: A loop lets you repeat the same steps many times without writing them again and again. Python has two main loops: for (repeat a set number of times, or once for each item) and while (repeat as long as something is true).
By the end you will be able to:
  • write a for loop with range(),
  • loop over a list or a string,
  • write a while loop and avoid endless loops,
  • use break to stop early and continue to skip a turn.

1. What is a loop?

Imagine you have to write "I will tidy my room" ten times. You could type the sentence ten times... or you could tell a friend: "repeat this sentence ten times." A loop is how you tell that to a computer.

Analogy: a loop is like the chorus of a song. You do not print the chorus lyrics again and again on the page — you just write "repeat chorus". The loop is Python's way of saying "do this part again."

2. The for loop with range()

The for loop repeats its body once for each value it is given. The helper range() gives Python a sequence of numbers to count through. Notice the colon : at the end of the line and the indentation (spaces) that shows which lines are inside the loop.

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

Expected output:

0
1
2
3
4

range(5) counts from 0 up to but not including 5, so we get 0, 1, 2, 3, 4 — that is five numbers. You can also give range() a start and a stop:

for i in range(1, 4):
    print(i)

Expected output:

1
2
3

And a third number sets the step (how much to jump each time):

for i in range(0, 10, 2):
    print(i)

Expected output:

0
2
4
6
8

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers