ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ
break, continue, and loop else
Sometimes a loop should end early: you found what you were looking for. Sometimes one
round should be skipped: a value is obviously wrong. In this lesson you'll do both with
break and continue, meet a loop feature that even experienced programmers misread,
and combine several loop plans into one program that handles messy input.
Stop at the first one: break
You met break in lesson 3.1: it leaves the loop at once. It's how you stop a search
as soon as it succeeds. Which number from 50 to 99 is the first multiple of 7?
for n in range(50, 100):
if n % 7 == 0:
print("First multiple of 7:", n)
breakIn the editor, press Escape then Tab to move on.
Without the break, it would print every multiple up to 98. Remove it and see. If
loops are inside each other, break leaves only the loop it's in; lesson 3.4 shows
that. And break belongs to loops only, not to if:
Skip one round: continue
skips the rest of the current round, and the loop carries on with the next one. Predict what this counts.
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
count = 0
for n in range(1, 8):
if n % 3 == 0:
continue
count = count + 1
print(count)Python prints
5
The loop runs for 1 to 7. For 3 and 6, continue skips the rest of the round, so count isn't increased. The other five numbers are counted.
That's how you skip bad values. Someone typed four prices, and two are negative by mistake. Skip those and add up the rest:
total = 0
count = 0
for i in range(4):
price = int(input("Price: "))
if price < 0:
continue
total = total + price
count = count + 1
print(f"{count} prices, {total} birr")In the editor, press Escape then Tab to move on.
One answer per line, given to input() in order.
The loop's else
A loop can have an else, and most people guess wrong about when it runs. Predict.
ውጤቱን ገምቱ
Decide before you look. Guessing wrong is how this sticks.
for letter in "Abel":
if letter == "e":
print("Found e")
break
else:
print("No e")
for letter in "Hana":
if letter == "e":
print("Found e")
break
else:
print("No e")Python prints
Found e No e
In the first loop, break runs, so the else is skipped. The second loop finishes without a break (there's no e in Hana), so its else runs.
A loop's else runs only when the loop finished without a break. It's not
"otherwise", and it doesn't mean "if the loop never ran". Many experienced
programmers misread it, so read it as "no break". It's useful for exactly this
job: a search, with a message when nothing was found.
ጥያቄ
When does a for loop's else block run?
Best so far
To find the highest score, keep the best so far: compare each new score with it, and replace it when the new one is higher. Start it below any possible score, so the first score always wins.
Keeping the highest
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.
When it asks, the user types 67, 82, then 45።
| Name | Value after line 1 |
|---|---|
| highestbest so far | -1new |
| icounter | not made yet |
| scorelatest value | not made yet |
Output so far
Step 1 of 14
Step 1 of 14. Line 1: highest = -1. highest is now -1, the best so far.
| Step | Line | highestbest so far | icounter | scorelatest value | Printed |
|---|---|---|---|---|---|
| 1 | 1 | -1 | not made yet | not made yet | |
| 2 | 2 | -1 | 0 | not made yet | |
| 3 | 3 | -1 | 0 | 67 | Score: 67 |
| 4 | 4 | -1 | 0 | 67 | |
| 5 | 5 | 67 | 0 | 67 | |
| 6 | 2 | 67 | 1 | 67 | |
| 7 | 3 | 67 | 1 | 82 | Score: 82 |
| 8 | 4 | 67 | 1 | 82 | |
| 9 | 5 | 82 | 1 | 82 | |
| 10 | 2 | 82 | 2 | 82 | |
| 11 | 3 | 82 | 2 | 45 | Score: 45 |
| 12 | 4 | 82 | 2 | 45 | |
| 13 | 2 | 82 | 2 | 45 | |
| 14 | 6 | 82 | 2 | 45 | Highest: 82 |
Three plans in six lines: i is a counter, score is the latest value, and
highest is the best so far. At step 12, 45 isn't higher than 82, so line 5 is
skipped and highest keeps 82.
መልመጃ
Exam averages
Read exam scores until the user types -1. Skip any score outside 0 to 100, with a
message. Then print how many scores were valid and their average, to one decimal. If
there were no valid scores, print No valid scores instead of crashing. Also try
it with only -1 in the Input box.
This is a famous problem, known as the Rainfall problem. Researchers have given it
to beginners for decades, and many studies report low success rates. The hard part
isn't the syntax; it's combining the plans. Yours needs five: a
stop value (-1 ends the loop with break), skipping bad input
(continue), a running total, a counter, and a guard so you never
divide by zero.
Score (-1 to stop): 72
Score (-1 to stop): 105
Skipped: 105
Score (-1 to stop): 88
Score (-1 to stop): 64
Score (-1 to stop): -1
3 scores, average 74.7Your code
total = 0
count = 0
# Ask until -1, skip scores outside 0-100, then print the count and averageIn 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.
total = 0
count = 0
while True:
score = int(input("Score (-1 to stop): "))
if score == -1:
break
if score < 0 or score > 100:
print("Skipped:", score)
continue
total = total + score
count = count + 1
if count > 0:
print(f"{count} scores, average {total / count:.1f}")
else:
print("No valid scores")ዋና ዋና ነጥቦች
breakleaves the loop at once; use it to stop a search when it succeeds.continueskips the rest of this round and goes on to the next; use it to skip bad values.- A loop's
elseruns only when the loop ended withoutbreak. Read it as "no break". - Best so far: compare each value with the best, and replace the best when the new one wins.
- Real programs combine plans: stop value, skip bad input, running total, counter, and a guard.