๐Ÿ Python for Teens & Beginners ยท Lesson 5 of 7

Loops: for and while

Google Classroom

Repeat code without copying it.

for with range

for i in range(5):
    print("Hello", i)
# prints Hello 0 โ€ฆ Hello 4

range(5) gives 0, 1, 2, 3, 4 โ€” five numbers, starting at 0. range(1, 11) gives 1 to 10. range(0, 20, 5) gives 0, 5, 10, 15.

Adding up in a loop

total = 0
for n in range(1, 101):
    total += n
print(total)  # 5050

while

answer = ""
while answer != "yes":
    answer = input("Are we there yet? ")
print("Finally!")

while repeats as long as the condition is true. Use it when you donโ€™t know how many times in advance.

break and infinite loops

break leaves a loop immediately. If a while condition never becomes false, the loop runs forever โ€” press Ctrl+C or the stop button to break out, then fix the condition.

Tip

๐Ÿ’ก Use for when you know how many times; use while when you repeat โ€œuntil something happensโ€.

โœ๏ธ Practice: your turn

  1. Print the 7 times table from 7ร—1 to 7ร—10
  2. Add up all the even numbers from 2 to 100
  3. Write a countdown from 10 to 1, then โ€œLiftoff!โ€
  4. Keep asking for a password until it is correct

โœ๏ธ Run Python in your browser, no install โ†—

๐Ÿง  Quick quiz

Answer all 4 questions correctly to mark this lesson as done.

1. What does range(4) give?
2. When is while better than for?
3. What does break do?
4. What does range(1, 11) give?

0 of 4 correct