🎯 Learning Objectives
After completing this section, you will understand:
- How to use while loops for repetitive tasks
- How to control loop execution with conditions
- Common loop patterns and use cases
- How to avoid infinite loops
⚡ Prerequisites
- Understanding of variables
- Knowledge of conditional statements
- Basic arithmetic operations
1. While Loops
A while loop executes a block of code repeatedly as long as a condition is true:
# Basic while loop
counter = 1
while counter <= 5:
print(counter)
counter += 1
1
2
3
4
5
Write a while loop that counts from 1 to 5:
# Write your code here
counter = 1
while counter <= 5:
print(counter)
counter += 1
2. Loop Conditions
The loop condition determines how long the loop continues:
Create a program that keeps asking for a password until "secret" is entered:
# Write your code here
password = ""
while password != "secret":
password = input("Enter password: ")
print("Correct password!")
3. Common Loop Patterns
Here are some common patterns you'll use with while loops:
Write a program that calculates the sum of numbers from 1 to 5:
# Write your code here
sum = 0
i = 1
while i <= 5:
sum += i
i += 1
print(f"Sum: {sum}")
4. Avoiding Infinite Loops
An infinite loop occurs when the loop condition never becomes False:
Create a number guessing game that stops when the user guesses 42:
# Write your code here
secret_number = 42
guess = 0
while guess != secret_number:
guess = int(input("Guess the number: "))
if guess < secret_number:
print("Too low!")
elif guess > secret_number:
print("Too high!")
print("Correct!")
🎉 Summary
You've learned about:
- Using while loops for repetition
- Creating and controlling loop conditions
- Common loop patterns
- Avoiding infinite loops
Total points: 4/4