🐍 Learn Python Basics
🔄 More Loops
🚀 While Loop?
Loops 🪄
So far, we’ve learned how to use **FOR** loops to repeat actions. Now it’s time to learn about **WHILE** loops! 🎉
A **while loop** keeps repeating the code as long as a certain condition is true. It’s like telling the bunny to keep hopping until it reaches the carrot! 🐰🥕
The key difference is that a **for loop** works by going through a sequence, while a **while loop** continues as long as the condition is true!
🤖 How Does a While Loop Work?
The `while` loop checks the condition before running the code. If the condition is true, it runs the code inside the loop. If it’s false, it stops.
Here’s a simple structure of a **while loop**:
while condition: # Code that gets executed as long as the condition is true
For example, if we want to make the bunny hop 10 times, we could write:
hop_count = 0 while hop_count < 10: # Keep hopping until hop_count is 10 print("🐰 Hop!") hop_count += 1 # Increase hop_count by 1 with each hop
In this example, the loop runs until `hop_count` reaches 10. Each time the loop runs, it prints "🐰 Hop!" and then increases `hop_count` by 1.
📌 Code and Output
Now, let’s try using the `while` loop in action! Below is the code for the bunny hop, and you can click the button to run it and see the output in the box below.
🐰 Bunny Hop Code:
hop_count = 0 while hop_count < 10: # Loop will repeat until the bunny has hopped 10 times print("🐰 Hop!") # Print bunny name as it hops hop_count += 1 # Increase hop_count by 1 with every loop iteration
💡 Why Use a While Loop?
- ✅ **Repeat tasks** until a condition is met
- ✅ **Flexible**: We don’t need to know how many times we’ll repeat—just keep going as long as the condition is true!
- ✅ **Useful for games**: Keep repeating actions like bunny hops or player movements until the game ends!
Now, let's try a fun game with the bunny and see how the loop works in action! 🐰🎮