TalentJR

Lesson 3

While Loops

Repeat until condition is met

1What Are While Loops?✨

While loops are a way to repeat a block of code as long as a certain condition is true. They help us run the same code multiple times without rewriting it!

2How Does It Work?🎯

A while loop starts with the keyword `while`, followed by a condition. The code inside the loop runs until the condition becomes false.

3Example:💡

💻 code
```
count = 0
while count < 5:
    print("Count is:", count)
    count += 1
```

In this example, the loop prints the count from 0 to 4.

4Using While Loops for User Input🚀

You can use while loops to keep asking for user input until they provide the right answer. This makes your programs more interactive!

5Example:🔍

💻 code
```
secret_number = 7
guess = 0
💻 code
while guess != secret_number:
    guess = int(input("Guess the secret number: "))
print("You guessed it!")
```

This loop keeps asking the user to guess until they get it right!

6Avoiding Infinite Loops⭐

Be careful! If the condition in a while loop never becomes false, the loop will run forever. This is called an infinite loop. Always ensure your loop will eventually stop!

7Example of an Infinite Loop:🧩

💻 code
```
while True:
    print("This will run forever!")
```

Always remember to change the condition within the loop to prevent this!

8When to Use While Loops🎈

  • ✓ Repeat actions until a condition changes
  • ✓ Create menus that keep showing until the user quits
  • ✓ Make games where players keep guessing until they succeed

Now you're ready to use while loops in your Python programs! Have fun coding!

🎯 Practice Challenges

Master While Loops by completing all 3 difficulty levels

🟢 EASY

While Loops - Easy Challenge

Start with the basics. Perfect for beginners!

🟡 MEDIUM

While Loops - Medium Challenge

Get more challenging. Build your confidence!

🔴 HARD

While Loops - Hard Challenge

Master this concept. Prove your skills!

🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →

Ready to Master While Loops? 🚀

Complete the challenges, take the quiz and keep your learning streak going!