🐍 Lesson 7: Loops

Repeat actions without copy-pasting

← Back to Python Basics

🔁 Why loops?

Imagine printing "Hello" 100 times. You wouldn't write 100 print() lines — you'd use a loop. A loop repeats a block of code so you don't have to.

🔂 The for loop with range()

range(n) gives the numbers 0 up to (but not including) n. A for loop walks through them one at a time:

for i in range(5): print(i) # prints 0 1 2 3 4 (each on its own line)

You can choose a start and stop:

for i in range(1, 6): print(i) # prints 1 2 3 4 5

📌 The loop variable

i is just a variable name that holds the current number each time around. You can call it anything — count, n, step.

📜 Looping over text and lists

for can step through each character in a string, or each item in a list:

for letter in "cat": print(letter) # c a t for fruit in ["apple", "banana", "cherry"]: print(f"I like {fruit}")

♾️ The while loop

A while loop keeps repeating as long as a condition stays true:

count = 3 while count > 0: print(count) count = count - 1 print("Blast off! 🚀")

Avoid infinite loops!

If the condition never becomes false, the loop runs forever and your program freezes. Always make sure something changes inside the loop (like count = count - 1) so it can eventually stop.

🛑 break and continue

  • break — jump out of the loop immediately.
  • continue — skip to the next time around.
for i in range(1, 10): if i == 5: break # stop the loop at 5 print(i) # prints 1 2 3 4

✅ What you learned

  • for loops repeat a set number of times, often with range().
  • for can step through strings and lists.
  • while loops repeat as long as a condition is true.
  • break stops a loop; continue skips to the next round.