More conditions, smarter loop
The problem...
Your while loop has one condition. It works. But real situations rarely have just one rule.
Keep going while the user hasn't quit AND the score is still positive. Stop when the time runs out OR the lives are gone. Skip if the value is NOT what you expect.
One condition isn't always enough.
The idea!
You already know and, or, and not from the if chapter. They work exactly the same way inside a while condition.
while with and
Both conditions must be true for the loop to keep running.
attempts = 0
password = "RedHorn"
answer = ""
while answer != password and attempts < 3:
answer = input("Enter password: ")
attempts += 1
if answer == password:
print("Access granted.")
else:
print("Too many attempts. Locked out.")
The loop runs while the password is wrong AND there are attempts left. Either condition failing — the loop stops.
while with or
At least one condition must be true for the loop to keep running.
health = 10
ammo = 0
while health > 0 or ammo > 0:
print(f"Health: {health} | Ammo: {ammo}")
health -= 3
ammo -= 1
The loop continues as long as health OR ammo is above zero. Both must fail for the loop to stop.
while with not
done = False
while not done:
answer = input("Type 'quit' to stop: ")
if answer == "quit":
done = True
print("Stopped.")
not done is true as long as done is False. The moment done becomes True — not done is False — loop stops.
Combining all three
score = 100
lives = 3
game_over = False
while score > 0 and lives > 0 and not game_over:
print(f"Score: {score} | Lives: {lives}")
score -= 20
lives -= 1
Three conditions. All must be true for the loop to continue. Any one of them failing — game over.
Heads up!
and— both must be True to keep loopingor— at least one must be True to keep loopingnot— inverts the condition- Complex conditions are evaluated left to right — use parentheses when in doubt
The mindset shift
Stop thinking: "My loop has one rule."
Start thinking: "My loop runs under a set of conditions — all of them matter."
What you should understand now
and,or,notwork inwhileconditions exactly as inifand— loop continues only when both conditions are Trueor— loop continues when at least one condition is Truenot— inverts — useful for flag variables likedoneorgame_over