TalentJR

🐍 Python for kids · Class 6 · Lesson 3 of 18 · Free

While Loops – Repeat Until Done

⏱ About 30 minutes · ▶ run real Python here — nothing to install · no sign-in

In this lesson you will

  • Write a while loop that changes its variable and stops at the right time.
  • Keep asking for input until the user types a valid answer or a stop value.
  • Use while True with break to leave a loop from the middle.

A shopkeeper keeps adding items to your bill until you say "that's all". He does not know in advance how many items you will buy. A while loop works the same way: it repeats until a condition tells it to stop.

How does a while loop work in Python?

A while loop checks its condition. If it is True, the indented block runs, and Python goes back to check again.

When the condition becomes False, the loop ends. Python jumps to the first line after the block.

Use while when you do not know how many rounds you need. Here, how many weeks to save for a cricket bat?

🎬 How Python thinks — step 1 of 33Python is about to run line 1
▶savings = 0
2weeks = 0
3while savings < 1000:
4 savings = savings + 150
5 weeks = weeks + 1
6 print("Week", weeks, "savings:", savings)
7print("Bat bought after", weeks, "weeks!")
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
Week 1 savings: 150
Week 2 savings: 300
Week 3 savings: 450
Week 4 savings: 600
Week 5 savings: 750
Week 6 savings: 900
Week 7 savings: 1050
Bat bought after 7 weeks!

💡 After week 6, savings is 900, which is still less than 1000. So one more round runs.

How do I keep asking until the user types a valid answer?

Users often type wrong values. A while loop can keep asking until the answer is acceptable.

The trick is to ask once before the loop. Then the loop asks again only while the answer is bad.

This is called input validation. Real apps, like ticket booking sites, do it all the time.

🎬 How Python thinks — step 1 of 10Python is about to run line 1
▶seats = int(input("How many seats (1 to 6)? "))
2while seats < 1 or seats > 6:
3 print("Please choose between 1 and 6.")
4 seats = int(input("How many seats (1 to 6)? "))
5print("Booked", seats, "seats.")
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
How many seats (1 to 6)? 9
Please choose between 1 and 6.
How many seats (1 to 6)? 0
Please choose between 1 and 6.
How many seats (1 to 6)? 4
Booked 4 seats.

What is a sentinel value in a while loop?

A sentinel is a special stop value, like 0 or "done". The loop keeps going until the user types it.

Below, a shopkeeper types prices one by one. Typing 0 ends the bill.

Notice that the sentinel itself is never added to the total.

🐍 Python — you can edit this code
Output
Price (0 to finish): 45
Price (0 to finish): 120
Price (0 to finish): 30
Price (0 to finish): 0
3 items, total bill 195 rupees

How do I use while True and break in Python?

while True: looks like a loop that never ends. It ends only when Python reaches a break.

This style is handy when the stop check sits in the middle of the loop, after an input.

Here the user gets three tries at a PIN. Both a correct PIN and a third wrong try leave the loop.

🐍 Python — you can edit this code
Output
Enter PIN: 1111
Enter PIN: 2468
Unlocked!

How do I skip a round with continue in a while loop?

continue jumps straight back to the condition check. The rest of the block is skipped for that round.

Be careful: update the loop variable before continue. Otherwise the loop may never move forward.

🐍 Python — you can edit this code
Output
1 2 4 5 7 8 10 
Multiples of 3 were skipped.

How do I add the digits of a number with a while loop?

% 10 gives the last digit of a number. // 10 removes the last digit.

So we take one digit, add it, and chop it off. We repeat while the number is above 0.

We do not know how many digits there are, so while is the perfect loop here.

🎬 How Python thinks — step 1 of 21Python is about to run line 1
▶number = 4728
2digit_sum = 0
3while number > 0:
4 digit = number % 10
5 digit_sum = digit_sum + digit
6 number = number // 10
7print("Sum of digits:", digit_sum)
📦 Variables (memory boxes)

No variables yet.

🖥️ Output
▌
✏️ Change this code and run it yourself
🐍 Python — you can edit this code
Output
Sum of digits: 21

🤔 Predict the output

Think like Python: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

x = 1
while x < 50:
    x = x * 3
print(x)

Question 2. What does this print?

count = 10
while count > 0:
    count = count - 4
print(count)

Question 3. What does this print?

n = 0
while True:
    n = n + 2
    if n > 5:
        break
    print(n)

🧩 Your challenge

Number guessing referee! The secret number is 37. Keep asking for guesses. Say "Too high" or "Too low" after each wrong guess. When the guess is right, print how many guesses it took.

Expected output (with the inputs given):
Your guess: 50
Too high
Your guess: 25
Too low
Your guess: 40
Too high
Your guess: 37
Correct! You took 4 guesses.
🐍 Python — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

laps = 0
while laps < 4:
    print("Running lap", laps + 1)
print("Race over")

No error message – it prints Running lap 1 forever (an infinite loop).

✅ Right

laps = 0
while laps < 4:
    print("Running lap", laps + 1)
    laps = laps + 1
print("Race over")

laps never changes inside the loop, so laps < 4 stays True forever. Always update the loop variable.

❌ Wrong

total = 0
price = int(input("Price (0 to stop): "))
while price != 0:
    total = total + price
print(total)

No error message – the program never stops, because it asks for a price only once.

✅ Right

total = 0
price = int(input("Price (0 to stop): "))
while price != 0:
    total = total + price
    price = int(input("Price (0 to stop): "))
print(total)

The input() must also be inside the loop. Otherwise price stays 50 and never becomes the stop value 0.

❌ Wrong

n = 5
while n > 0
    print(n)
    n = n - 1

SyntaxError: expected ':'

✅ Right

n = 5
while n > 0:
    print(n)
    n = n - 1

A while line needs a colon at the end, just like if and for.

📌 Remember

  • A while loop repeats as long as its condition is True.
  • Something inside the loop must change, or it runs forever.
  • Ask once before the loop and again inside it to validate input.
  • A sentinel value, like 0, tells the loop that the user is done.
  • while True with break lets you stop from the middle of a loop.
  • continue skips the rest of one round; update your variable before it.

Finished the quiz and the challenge?

Questions students ask

When should I use a while loop instead of a for loop?

Use while when you do not know how many repeats you need. For example, keep asking until the answer is right.

How do I stop an infinite while loop?

Press the Stop button or reload the page. Then check that the loop variable changes, so the condition can become False.

Is while True bad in Python?

No, it is common and useful. Just make sure every path through the loop can reach a break.

Can a while loop run zero times?

Yes. If the condition is False the very first time, Python skips the block completely.