انتقل للمحتوى
Robo EgyptRobo Egypt
☰ Course contents
Robo Python: home
0. Lab tour1
1. The start5
2. Variables and input5
3. Conditions5
4. Loops5
5. Lists4
6. Functions4
7. Drawing with the turtle3
8. The project: the guess-the-number game3
9. Strings in depth1
10. Dictionaries (dict)3
11. Randomness and errors3
12. Classes and objects (class)2
13. Pro drawing and charts3
14. The final project: the quiz game2

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:
3
2
1
Launch! 🚀
🐍 Open the code in Robo Python ↗
The example in Robo Python: the code on the right and what appeared on the left
The example in Robo Python: the code on the right and what appeared on the left
📌 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.

🐍 Add until zero
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:
Number (0 to stop): 10
Number (0 to stop): 15
Number (0 to stop): 5
Number (0 to stop): 0
Total: 30
🐍 Open the code in Robo Python ↗
✍️ Practise
Try the lesson's examples here: copy the code, change it, and click ▶ Run.
✍️ Practise here in the lessonor open the lab in a new page ↗

🎯 Challenge yourself

Easy

while: print 1, 2, 4, 8 … until it goes past 100.

👀 Show the solution
🐍 Solution
n = 1
while n <= 100:
    print(n)
    n = n * 2
🖥️ The output in Robo Python:
1
2
4
8
16
32
64
🐍 Open the code in Robo Python ↗

Result: 1 2 4 8 16 32 64

Medium

Ask until the user types yes.

👀 Show the solution

When the program asks, we type: no, then no, then yes.

🐍 Solution
while True:
    a = input("Ready? ")
    if a == "yes":
        break
print("Let's go!")
🖥️ The output in Robo Python:
Ready? no
Ready? no
Ready? yes
Let's go!
🐍 Open the code in Robo Python ↗

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
🐍 Solution
n = 1000
count = 0
while n >= 1:
    n = n / 2
    count = count + 1
print(count)
🖥️ The output in Robo Python:
10
🐍 Open the code in Robo Python ↗

Result: 10 times

Finished the lesson? Mark it so your progress counts.