while and break
Section 4: LoopsLesson 4.3 · ⏱ 8 min
while repeats as long as the condition is true. And break leaves the loop at once.
count = 3
while count > 0:
print(count)
count = count - 1
print("Launch! 🚀")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗3 2 1 Launch! 🚀

📌 Note
If the condition never changes, the loop never ends. Click “Stop” to stop it.
📌 Another example: add until zero
We add numbers until the user types 0.
When the program asks, we type: 10, then 15, then 5, then 0.
total = 0
while True:
n = int(input("Number (0 to stop): "))
if n == 0:
break
total = total + n
print("Total:", total)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Number (0 to stop): 10 Number (0 to stop): 15 Number (0 to stop): 5 Number (0 to stop): 0 Total: 30
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
while: print 1, 2, 4, 8 … until it goes past 100.
👀 Show the solution🙈 Hide the solution
n = 1
while n <= 100:
print(n)
n = n * 2
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗1 2 4 8 16 32 64
Result: 1 2 4 8 16 32 64
Medium
Ask until the user types yes.
👀 Show the solution🙈 Hide the solution
When the program asks, we type: no, then no, then yes.
while True:
a = input("Ready? ")
if a == "yes":
break
print("Let's go!")
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗Ready? no Ready? no Ready? yes Let's go!
Result: Let's go! after yes.
Hard
How many times do we divide 1000 by 2 until it is less than 1?
👀 Show the solution🙈 Hide the solution
n = 1000
count = 0
while n >= 1:
n = n / 2
count = count + 1
print(count)
🖥️ The output in Robo Python:
🐍 Open the code in Robo Python ↗10
Result: 10 times

