Python ยท Lesson 4 of 5

๐Ÿ” Loops

Repeat code without writing it again and again.

A for loop repeats code. range(5) gives the numbers 0, 1, 2, 3, 4.

for i in range(1, 6):
    print("Star", i, "โญ")
OUTPUTStar 1 โญ Star 2 โญ Star 3 โญ Star 4 โญ Star 5 โญ

A while loop repeats as long as a condition stays true.

count = 3
while count > 0:
    print(count)
    count = count - 1
print("Blast off! ๐Ÿš€")
OUTPUT3 2 1 Blast off! ๐Ÿš€

๐Ÿ’ก Always change the variable inside a while loop, or it will never stop.

โœ๏ธ Your turn

Open this example in the playground, change it and run it.

โ–ถ Try it yourself

๐Ÿง  Quick quiz

How many times does for i in range(3) run?