Python Lesson 9: Loops (for and while)
Loops repeat code automatically. Instead of writing the same line 100 times, you write it once and tell Python to repeat. This is one of the most powerful ideas in programming.
for Loop
# Print numbers 0 to 4
for i in range(5):
print(i)
# Output: 0 1 2 3 4
# Print 1 to 10
for i in range(1, 11):
print(i)
# Count by 2s (step)
for i in range(0, 10, 2):
print(i)
# Output: 0 2 4 6 8
Loop Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I love {fruit}!")
# Output:
# I love apple!
# I love banana!
# I love cherry!
while Loop
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1 # ALWAYS change the variable!
# Output: Count: 1, Count: 2 ... Count: 5
# Forgetting count += 1 creates an INFINITE LOOP!
break and continue
# break — exit the loop immediately
for i in range(10):
if i == 5:
break
print(i)
# Output: 0 1 2 3 4
# continue — skip this iteration, keep looping
for i in range(10):
if i % 2 == 0:
continue # skip even numbers
print(i)
# Output: 1 3 5 7 9
Number Guessing Game with Loop
secret = 7
attempts = 0
while True:
guess = int(input("Guess (1-10): "))
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Correct! Got it in {attempts} attempts!")
break
🏋️ Practice Task
Print the multiplication table for any number the user enters. Show 1xN through 10xN. Example: if user enters 7, print: “7 x 1 = 7”, “7 x 2 = 14”, …, “7 x 10 = 70”
💡 Hint: Use for i in range(1, 11): and inside: print(f”{n} x {i} = {n*i}”)