Welcome to Module 3! So far, your programs run once and then quit. But what if you wanted to print “I love Python” 1,000 times? Or what if you wanted to keep a game running until the player loses?
In this module, we learn about Loops. Loops allow you to repeat a block of code over and over again.
1. The while Loop (The “Keep Going” Loop)
A while loop is like a treadmill. It keeps running as long as a certain condition is True. The moment that condition becomes False, the loop stops.
Shutterstock
The Code:
Python
count = 1
while count <= 5:
print("This is lap number " + str(count))
count = count + 1 # We add 1 to the count so the loop eventually ends!
print("Race finished!")
⚠️ The Infinite Loop Danger: If you forget to change the variable (like
count = count + 1), the condition will stayTrueforever. Your computer will keep printing until the program crashes! If this happens, press Ctrl + C to stop it.
2. The for Loop (The “Counting” Loop)
A for loop is used when you know exactly how many times you want to repeat something. It is very common to use the range() function with it.
The Code:
Python
# This will print numbers from 0 to 4
for i in range(5):
print("Counting: " + str(i))
Why use for instead of while? * Use while when you don’t know when the end will happen (like waiting for a user to type “quit”).
- Use
forwhen you have a specific list or number of steps to follow.
3. Breaking and Continuing
Sometimes you need to jump out of a loop early.
break: This stops the loop immediately, even if the condition is still True.continue: This skips the rest of the current lap and jumps back to the start of the next one.
4. The “Game Loop” Pattern
Most software uses a while loop to stay alive. Here is how a simple menu works:
Python
running = True
while running:
user_input = input("Type 'exit' to quit or anything else to stay: ")
if user_input == "exit":
running = False # This breaks the loop
print("Goodbye!")
else:
print("Still here!")
🎓 Module 3 Final Project: “The Number Guessing Game” 🎲
This project combines everything from Modules 1, 2, and 3!
The Challenge:
- Create a variable called
secret_numberand set it to7. - Use a
whileloop to keep asking the user to “Guess the number.” - If the guess is too low, print “Too low!”
- If the guess is too high, print “Too high!”
- If the guess is correct, print “You won!” and break the loop.
The Solution:
Try to build the logic first!
Python
secret_number = 7 guessing = True
while guessing: guess = int(input(“Guess a number between 1 and 10: “))
if guess < secret_number: print("Too low!") elif guess > secret_number: print("Too high!") else: print("You got it!") guessing = False # Or use 'break'
Next Up: In Module 4, we learn how to package our code into Functions so we can reuse it like a pro.
