Skip to content

ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ

while loops

4 min read

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.

count = 3
while count > 0:
print(count)
count = count - 1
print("Go!")
Names and their values after line 1
NameValue after line 1
countcounter3new

Output so far

Step 1 of 12

Step 1 of 12. Line 1: count = 3. count is now 3, the counter.

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.

savings = 500
while savings < 1000:
savings = savings + 300
print("Saved:", savings)
print("Goal reached")
Names and their values after line 1
NameValue after line 1
savingsrunning total500new

Output so far

Step 1 of 9

Step 1 of 9. Line 1: savings = 500. savings is now 500, the running total.

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.

Output
PIN: 1111
PIN: 2222
PIN: 3333
Card locked

Your code

MAX_ATTEMPTS = 3
PIN = "4321"
attempts = 0
entered = ""
# Loop as long as there are tries left and the PIN is wrong

In the editor, press Escape then Tab to move on.

One answer per line, given to input() in order.

መፍትሄውን አሳይ

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")

ዋና ዋና ነጥቦች

  • while repeats 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:, and break out 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.