Python While Loops 🔄
Repeating Code
Python has two primitive loop commands: while loops and for loops. With the while loop we can execute a set of statements as long as a condition is true.
🥣 Analogy: Eating Cereal
Think of a while loop like eating a bowl of cereal.
While the bowl is not empty:
1. Take a spoonful.
2. Eat it.
3. Check if the bowl is empty again.
When the bowl is empty (Condition becomes False), you stop eating.
✨ Basic While Loop
i = 1
while i < 6:
print(i)
i += 1 # IMPORTANT: Increment i, or the loop will continue forever🛑 Break and Continue
Break
Stop the loop even if the while condition is true.
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1Continue
Stop the current iteration, and continue with the next.
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)🔚 The else Statement
With the else statement we can run a block of code once when the condition no longer is true.
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")🎯 Real-World Application: Game Loop
Video games run inside a giant while loop that keeps running until the player quits.
game_over = False
while not game_over:
player_action = input("Do you want to (p)lay or (q)uit? ")
if player_action == "q":
game_over = True
print("Thanks for playing!")
else:
print("Playing game frame...")✨ Pro Tip: "Do-While" Emulation
Python doesn't have a built-in do-while loop, but you can emulate it using while True and break.
while True:
user_input = input("Type 'exit' to stop: ")
if user_input == 'exit':
break
print(f"You typed: {user_input}")⚠️ Infinite Loops
If you forget to update the variable used in the condition, the loop will run forever and crash your program. To stop an infinite loop in the terminal, press Ctrl + C.