ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ
while loops
So far every line of your programs has run once at most. But a lot of real work is
repetition: count down, keep asking until the answer makes sense, keep saving until
you reach a goal. In this lesson you'll make Python repeat lines with while, and
learn exactly when it stops, which is where most loop bugs come from.
Every lesson in this module works fully in your browser.
Repeat as long as
Predict what this prints, line by line.
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
count = 3
while count > 0:
print(count)
count = count - 1
print("Go!")Python prints
3 2 1 Go!
The indented lines repeat as long as count > 0. Each round prints count and lowers it by 1. When count reaches 0, the condition is False, so Python skips the block and moves on to Go!
Read while aloud as "as long as": "as long as count is more than 0, print it and
take one off". The condition isn't when to stop; it's when to keep going. The
indented block is the body of the
,
and each time through it is a round. Step through it:
A counter counting down
Press Next to run one line at a time and watch each name change.Each row is one step: the line that just ran, and every name's value after it.
| Name | Value after line 1 |
|---|---|
| countcounter | 3new |
Output so far
Step 1 of 12
Step 1 of 12. Line 1: count = 3. count is now 3, the counter.
| Step | Line | countcounter | Printed |
|---|---|---|---|
| 1 | 1 | 3 | |
| 2 | 2 | 3 | |
| 3 | 3 | 3 | 3 |
| 4 | 4 | 2 | |
| 5 | 2 | 2 | |
| 6 | 3 | 2 | 2 |
| 7 | 4 | 1 | |
| 8 | 2 | 1 | |
| 9 | 3 | 1 | 1 |
| 10 | 4 | 0 | |
| 11 | 2 | 0 | |
| 12 | 5 | 0 | Go! |
count goes up or down by one each round. A name used like that is a
counter, the first of several plans you'll learn to spot in loops. Watch the
marked line jump back to line 2 after every round: that's where the decision happens.
The condition is checked at the top
Python checks the condition only at the start of each round, never in the middle. Here the goal is reached halfway through a round. Does the round stop?
Step through it
Press Next to run one line at a time and watch each name change.Each row is one step: the line that just ran, and every name's value after it.
| Name | Value after line 1 |
|---|---|
| savingsrunning total | 500new |
Output so far
Step 1 of 9
Step 1 of 9. Line 1: savings = 500. savings is now 500, the running total.
| Step | Line | savingsrunning total | Printed |
|---|---|---|---|
| 1 | 1 | 500 | |
| 2 | 2 | 500 | |
| 3 | 3 | 800 | |
| 4 | 4 | 800 | Saved: 800 |
| 5 | 2 | 800 | |
| 6 | 3 | 1100 | |
| 7 | 4 | 1100 | Saved: 1100 |
| 8 | 2 | 1100 | |
| 9 | 5 | 1100 | Goal reached |
At step 6, savings is 1100 and the condition is already false, but line 4 still
runs. The round always finishes; Python only notices at line 2. savings grows by
adding to itself each round, a plan called a running total.
ጥያቄ
When does Python check a while loop's condition?
A loop that never stops
If nothing in the body moves the condition towards false, the loop never ends. Here the counter goes the wrong way. Run it and wait five seconds.
count = 3
total = 0
while count > 0:
total = total + count
count = count + 1
print(total)In the editor, press Escape then Tab to move on.
You'll see "Stopped after 5 seconds. Is there an infinite loop?" count goes 3, 4,
5, … and is always more than 0. Change + 1 to - 1 on line 5 and it prints 6.
When a loop won't stop, check that its body changes what the condition is about.
Ask until it's valid
Users type mistakes. A common plan is to keep asking until the answer is valid:
while True:
score = int(input("Score (0-100): "))
if 0 <= score <= 100:
break
print("Please enter a score from 0 to 100.")
print("Saved:", score)In the editor, press Escape then Tab to move on.
One answer per line, given to input() in order.
while True: would run forever on its own. The way out is
,
which leaves the loop at once. So: ask, and if the answer is good, break out;
otherwise complain and go round again. score is a latest value: each round
replaces it with the newest answer. You'll use this "ask until valid" plan in almost
every program that takes input. Forget the int(), and the first comparison fails:
How many months?
Plans combine. Hana saves 700 birr a month towards a 5,000 birr phone. How many months
until she has enough? savings is a running total and months is a counter:
goal = 5000
deposit = 700
savings = 0
months = 0
while savings < goal:
savings = savings + deposit
months = months + 1
print(f"{months} months: {savings} birr")In the editor, press Escape then Tab to move on.
Try a deposit of 1,000: exactly 5 months. Then try 5,000 as the deposit.
መልመጃ
Three tries at the PIN
A card allows three tries. Keep asking for the PIN as long as there are tries left
and the PIN is wrong. Afterwards, print Welcome or Card locked. MAX_ATTEMPTS
and PIN never change: names like that are constants, written in capitals.
Try 1111 then 4321 as well.
PIN: 1111
PIN: 2222
PIN: 3333
Card lockedYour code
MAX_ATTEMPTS = 3
PIN = "4321"
attempts = 0
entered = ""
# Loop as long as there are tries left and the PIN is wrongIn the editor, press Escape then Tab to move on.
One answer per line, given to input() in order.
መፍትሄውን አሳይHide the solution
This is one way to solve it, not the only one. If yours prints the same thing, it works.
MAX_ATTEMPTS = 3
PIN = "4321"
attempts = 0
entered = ""
while attempts < MAX_ATTEMPTS and entered != PIN:
entered = input("PIN: ")
attempts = attempts + 1
if entered == PIN:
print("Welcome")
else:
print("Card locked")ዋና ዋና ነጥቦች
whilerepeats its block as long as the condition is true.- The condition is checked only at the start of each round; a round always finishes.
- If the body never moves the condition towards false, the loop runs forever. The site stops it after 5 seconds; Ctrl+C stops it in a terminal.
- "Ask until valid":
while True:, andbreakout when the answer is good. - Loop plans have names: a counter goes up by one, a running total adds to itself, a latest value holds the newest answer, a constant never changes.