Python for Beginners: Learn to Code from Zero · Lesson 5 of 10

Lesson 5: Loops: Repeating Work with for and while

Repeat actions without copying code. Learn for loops, range(), while loops, break and continue.

Lesson 5: Loops: Repeating Work with for and while

Imagine printing a multiplication table. You could write twelve print() lines, or you could use a loop and write one.

The for loop

for repeats once for each item. range(1, 6) gives the numbers 1, 2, 3, 4, 5 (it stops before the second number).

for number in range(1, 6):
    print(number)

Output:

1
2
3
4
5

A multiplication table:

for i in range(1, 6):
    print(f"7 x {i} = {7 * i}")

Output:

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

You can loop over text and lists too:

for letter in "Nepal":
    print(letter)

Output:

N
e
p
a
l

Adding things up

total = 0
for n in range(1, 11):
    total = total + n
print(total)

Output:

55

The while loop

while keeps repeating as long as a condition stays true. Be careful: something inside the loop must eventually make the condition false, or it will run forever.

count = 3
while count > 0:
    print(count)
    count = count - 1
print("Go!")

Output:

3
2
1
Go!

break and continue

  • break leaves the loop immediately.
  • continue skips the rest of this round and starts the next.
for n in range(1, 10):
    if n % 2 == 0:
        continue      # skip even numbers
    if n > 7:
        break         # stop completely
    print(n)

Output:

1
3
5
7

Try it yourself

  1. Print the even numbers from 2 to 20.
  2. Add up all the numbers from 1 to 100.
  3. Print a countdown from 10 to 1 using a while loop.

Next lesson: storing many values in lists and dictionaries.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 5: Loops: Repeating Work with for and while | MeroSir