Lesson 8: Loops
Master automation by learning how to repeat code segments using while and for loops.
Lesson 8: Loops
Imagine you had to print "I will not talk in class" 100 times. Typing that manually would be boring and prone to mistakes. This is where Loops come in. Loops allow us to repeat a block of code as many times as we need, automatically.
Lesson Overview
In this lesson, we will cover:
- The
whileLoop: Carrying on while a condition is True. - The
forLoop: Repeating for a specific sequence. - The
range()Function: Generating numbers for loops. - Infinite Loops: What they are and how to avoid them.
- Controlling Loops: Using
breakandcontinue.
1. The while Loop
A while loop runs as long as a condition is True. It’s like saying: "While I'm hungry, I keep eating."
count = 1
while count <= 5:
print(f"Number: {count}")
# This is very important! We must change the variable
# or the loop will never end.
count = count + 1
print("Done!")
Warning: Infinite Loops! If you forget to increment count, the computer will keep printing "Number: 1" forever. If this happens, press Ctrl+C in your terminal to kill the program!
2. The for Loop
A for loop is used to iterate over a sequence (like a list of names or a range of numbers). It is more common than while loops in Python.
# Print every letter in a word
for letter in "Python":
print(letter)
3. The range() Function
We often use for loops with range() to repeat an action a specific number of times.
# range(5) starts at 0 and goes up to (but not including) 5.
for i in range(5):
print(f"Iteration {i}")
Wait, 4? Yes! In programming, we almost always start counting at 0. So range(5) gives us: 0, 1, 2, 3, 4.
4. Loop Control: break and continue
break: Stop the loop immediately.continue: Skip the current step and go to the next one.
# Stopping early
for n in range(10):
if n == 5:
break # Exit the loop when we hit 5
print(n)
# Skipping a step
for n in range(5):
if n == 2:
continue # Don't print 2, just move on to 3
print(n)
Practice Exercise: The Countdown
Create a file named countdown.py. Write a program that:
- Asks the user for a starting number (e.g., 10).
- Uses a
whileloop to count down from that number to 1. - Prints
"Blast off!"once the loop finished.
Bonus: Use a for loop with range() to do the same thing! (Hint: Look up range(start, stop, step)).
Quick Knowledge Check
- What is the main difference between a
whileloop and aforloop? - What happens if the condition of a
whileloop never becomesFalse? - What is the result of
range(3)? - What command is used to exit a loop completely?
Key Takeaways
- Loops automate repetitive tasks.
whileloops are condition-based;forloops are sequence-based.range()is the best friend of theforloop.- Always ensure your
whileloops have a way to terminate!
What’s Next?
We’ve covered variables, logic, and loops. Now it’s time to organize these tools! In Lesson 9, we’ll learn how to Write Simple Programs that solve real problems by combining everything we’ve learned.