Lesson 7: while
Loops
Topics Covered:
- Understanding loops and repetition
- Using
while
loops to repeat code - Controlling loops with conditions and
break
What is a Loop?
Loops repeat code. A while
loop runs as long as a condition is True
:
count = 1
while count <= 5:
print("Count is", count)
count += 1
Infinite Loops
If the condition never becomes False
, the loop will run forever. Use break
to stop:
while True:
command = input("Type 'exit' to quit: ")
if command == "exit":
break
Using a Condition to Control a Loop
Keep asking until the right answer is given:
password = ""
while password != "python":
password = input("Enter the password: ")
print("Access granted!")
Activity: Count Down
Write a loop that counts down from 10 to 1:
num = 10
while num > 0:
print(num)
num -= 1
print("Blast off!")
Challenge Task
- Ask the user a math question like “What’s 2 + 2?”
- Repeat the question until they get it right
answer = 0
while answer != 4:
answer = int(input("What is 2 + 2? "))
print("Correct!")