๐ Python for Teens & Beginners ยท Lesson 5 of 7
Loops: for and while
Repeat code without copying it.
for with range
for i in range(5):
print("Hello", i)
# prints Hello 0 โฆ Hello 4range(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) # 5050while
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
- Print the 7 times table from 7ร1 to 7ร10
- Add up all the even numbers from 2 to 100
- Write a countdown from 10 to 1, then โLiftoff!โ
- Keep asking for a password until it is correct
๐ง Quick quiz
Answer all 4 questions correctly to mark this lesson as done.
0 of 4 correct
All lessons in Python for Teens & Beginners
- ๐ 1. Your first programprint, quotation marks, and error messages
- ๐ฆ 2. Variables and inputStore information and ask the user
- ๐งฎ 3. Math in PythonOperators, division, remainder and powers
- ๐ 4. Conditions: if and elseThe program decides by itself
- ๐ 5. Loops: for and whileRepeat code without copying it
- ๐ 6. ListsMany values in one variable
- ๐ฒ 7. Project: a guessing gameThe computer picks a number, and you guess