Now print 1 to 5000. Copy and paste is not a plan. And what about "print the numbers from 1 up to whatever the user types"? You cannot even write that program by copying, because you do not know how many lines to copy.
Repeating a block of code is called looping or iteration. Each single run through the block is one iteration, or one pass. Python has two kinds of loop:
while repeats as long as a condition is true. This chapter.
for repeats once for each item in a collection. The next chapter.
It looks almost exactly like an if: a keyword, a condition, a colon and an indented block. The difference is one single step. After an if block finishes, the program moves on. After a while block finishes, the program jumps back up and tests the condition again.
If it is true, run the whole block, then go back to step 1.
If it is false, skip the block and continue after the loop.
Tracing the loop
A trace table is the best way to understand any loop. Write one row per test of the condition:
Pass
count when tested
count <= 5
Prints
count after the block
1
1
True
1
2
2
2
True
2
3
3
3
True
3
4
4
4
True
4
5
5
5
True
5
6
—
6
False
the loop ends
Two things to notice. The condition is tested six times for five passes: the final test is the one that fails and ends the loop. And when the loop is over, count is 6, not 5. The loop stops becausecount went past the limit.
The three ingredients
Every counting loop has three parts, and forgetting any of them is a bug:
count = 1 ◄── 1. START: a first value for the loop variable
while count <= 5: ◄── 2. CONDITION: when should the loop keep going?
print(count)
count = count + 1 ◄── 3. UPDATE: change what the condition tests
Forget the...
What happens
start
NameError: the condition uses a name that does not exist yet
condition (or get it wrong)
the loop runs too many times, too few, or not at all
update
the condition never becomes false: an infinite loop
The update is usually written with the shorthand from Chapter 3: count += 1.
Quick check
How many lines does this print, and what is n afterwards?
n = 10 ⏎ while n > 0: ⏎ (block) print(n) then n -= 3
Show the answer
Answer: four lines: 10, 7, 4, 1. After the fourth pass n is -2, the test -2 > 0 fails, and the loop ends. n is -2.
A counting loop has a start, a condition and an update. The line without indentation after the block runs once, when the loop is over.
Fill in the blank
Fill in the comparison operator so that the loop prints the numbers shown in the target.
n=1whilen4:
print(n)n+=1
The finished program prints:
Target
1
2
3
4
Check the last pass: the condition must still be true when n is 4.
It must be false when n is 5. Which operator means "less than or equal to"?
n=1whilen<=4:
print(n)n+=1
n <= 4 is true for 1, 2, 3 and 4, and false for 5, so the block runs four times.
13.3 The condition is only checked at the top
This rule causes surprises, so it gets its own section. Python tests the condition once per pass, before the block. It does not watch the condition while the block is running.
count=1whilecount<=3:
count=count+10print("Inside the loop, count is",count)print("After the loop")
Output
Inside the loop, count is 11
After the loop
After the first line of the block, count is 11 and the condition is already false. But the print still runs, because the block always finishes its current pass. The condition is only looked at again when the program goes back to the top.
A loop can run zero times
Because the test comes first, the block might never run at all:
count=10whilecount<=5:
print(count)print("Done")
Output
Done
The very first test, 10 <= 5, is false. This is often exactly what you want: "while there are items left to process" should do nothing when there are none.
The condition is tested before the first pass too.
Is 0 > 0 true or false?
The answer is: Only Shop closed
The very first test is false, so the block runs zero times. The program goes straight to the line after the loop.
13.4 Infinite loops
If the condition never becomes false, the loop never ends. This is an infinite loop, and every programmer writes one sooner or later.
count=1whilecount<=5:
print(count)
Output
The update is missing. count is 1 for ever, 1 <= 5 is true for ever, and the screen fills with 1s until you stop it.
Other ways to build one by accident:
count=1whilecount!=10: # 1, 3, 5, 7, 9, 11, 13, ... jumps straight over 10count+=2count=5whilecount>0: # going the wrong way: 6, 7, 8, ...count+=1count=1whilecount<=5:
print(count)count+=1# not indented: this is AFTER the loop, so it never runs
Output
The last one is the indentation trap from Chapter 11 in a new form. The update exists, but it is outside the block.
An infinite loop that is not a mistake
Some programs are meant to run until somebody quits them: a game, a web server, a cash machine, the Python shell itself. For those, an endless loop is the right design, and it is written openly:
whileTrue:
...
Output
True is always true, so this loop never ends by its condition. It ends from the inside, with break, which is coming in section 13.7.
Practice 13.4
Multiple choice
Each loop below starts with count = 1. Three of them end. Which one never ends?
Loop 1:while count < 10: with the block count += 2
Loop 2:while count != 10: with the block count += 2
Loop 3:while count != 10: with the block count += 3
Loop 4:while count <= 10: with the block count *= 2
Write down the first six values of count for each loop.
A loop with != stops only if count lands exactly on 10. A loop with < or <= stops as soon as count passes the limit.
The answer is: Loop 2
With steps of 2 from 1, count is always odd: 1, 3, 5, 7, 9, 11. It jumps over 10, so count != 10 stays true for ever.
Multiple choice
A program is stuck in an infinite loop. What do you press, after clicking in the terminal, to stop it?
The chapter gives this in a warning box in section 13.4.
The program then ends with a KeyboardInterrupt.
The answer is: Ctrl+C
Ctrl+C sends a signal to the program, and Python ends it with a KeyboardInterrupt.
13.5 The standard patterns
Most loops you will ever write are one of a few shapes. Learn the shapes and you can write a loop without thinking hard.
Normally print ends by moving to a new line. end=" " tells it to end with a space instead, so the numbers appear side by side. The empty print() after the loop finishes the line. You will learn everything print can do in → Chapter 16.
Adding up: the accumulator
To total a series of values, keep a running total. Start it at zero before the loop and add to it on each pass. A variable used this way is called an accumulator.
total=0number=1whilenumber<=5:
total=total+numbernumber+=1print("Sum of 1 to 5:",total)
Output
Sum of 1 to 5: 15
Pass
number
total before
total after
1
1
0
1
2
2
1
3
3
3
3
6
4
4
6
10
5
5
10
15
The key rule: the accumulator is created before the loop. If total = 0 were inside the block, it would be reset to zero on every pass.
The starting value depends on the operation. For a sum it is 0. For a product it is 1, because multiplying by 0 would wipe everything out:
A counter is an accumulator that goes up by one each time something happens. Here, how many numbers from 1 to 30 are divisible by 7?
found=0number=1whilenumber<=30:
ifnumber%7==0:
found+=1number+=1print("Multiples of 7:",found)
Output
Multiples of 7: 4
An if inside a loop is completely normal. Notice the indentation: found += 1 is inside the if (eight spaces), while number += 1 is inside the loop but outside the if (four spaces), so it runs on every pass. Putting the update inside the if by accident would make an infinite loop.
Keeping the best so far
To find the largest value, remember the best one seen so far and replace it whenever a better one appears:
largest=0number=int(input("A positive number (0 to stop): "))whilenumber!=0:
ifnumber>largest:
largest=numbernumber=int(input("A positive number (0 to stop): "))print("Largest:",largest)
Output
A positive number (0 to stop): 12
A positive number (0 to stop): 45
A positive number (0 to stop): 7
A positive number (0 to stop): 0
Largest: 45
Quick check
What is wrong with this attempt to add the numbers 1 to 100?
n = 1 ⏎ while n <= 100: ⏎ (block) total = 0, then total += n, then n += 1
Show the answer
Answer:total = 0 is inside the loop, so the total is thrown away at the start of every pass. At the end, total is just 100. The accumulator must be created before the loop.
Practice 13.5
Fill in the blank
This loop multiplies the numbers 1 to 4. Fill in the starting value of the accumulator.
A product starts at 1, because multiplying by 1 changes nothing. A start of 0 would make every result 0.
Fix the bug
The user types positive prices, then 0 to stop. The program should print the largest price. Now it prints the last price that was typed. Fix it.
With the replies 12 then 45 then 7 then 0, the program prints the lines below. Your program must print exactly these lines.
Example run
Largest: 45
Output
largest should change only when the new price beats the best one so far.
Put the line largest = price inside an if that compares the two values.
largest=0price=int(input("Price (0 to stop): "))whileprice!=0:
ifprice>largest:
largest=priceprice=int(input("Price (0 to stop): "))print("Largest:",largest)
The pattern "best so far" replaces the stored value only when a better one appears. Without the if, every price replaces it.
Write code
Sum of the even numbers. Ask for a whole number n. Print one line: the sum of the even numbers from 2 up to n (with n itself when it is even). For 10 that is 2 + 4 + 6 + 8 + 10. When n is below 2, the sum is 0.
With the reply 10, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Sum: 30
Output
Create the total before the loop, with the value 0.
Start the loop variable at 2 and add 2 on every pass, or go up by 1 and add only when number % 2 == 0.
This is the accumulator pattern with a step of 2. When n is below 2 the loop runs zero times and the total stays 0.
13.6 Loops that depend on the user
A counting loop knows how many passes it will make. Many loops do not: they continue until the user signals the end. A special value that means "stop" is called a sentinel.
The largest-number program above is a sentinel loop, with 0 as the sentinel. Look at its shape, because it is very common:
number = int(input(...)) ◄── read the FIRST value before the loop
while number != 0: ◄── test for the sentinel
... use number ...
number = int(input(...)) ◄── read the NEXT value, last in the block
The value is read in two places: once before the loop, so that the first test has something to look at, and once at the end of the block, as the update. The first read is sometimes called the priming read.
Having the same line twice is a little unsatisfying. There are two cleaner ways to write it, and you will meet both: while True with break (section 13.7) and the walrus operator (section 13.9).
A sentinel must not be real data
In the example, 0 cannot be one of the numbers. If zero were a legitimate value, you would need a different sentinel, such as an empty line or the word done. Choose a sentinel that can never be mistaken for data.
Practice 13.6
Put the lines in order
Put the lines in order to build a sentinel loop with a priming read. The word stop ends the loop and must not be printed. The indentation of each line is fixed.
With the replies tea then milk then stop, the program in the right order prints:
Target
TEA
MILK
Finished
word=input("Word (stop to end): ")
print(word.upper())
whileword!="stop":
word=input("Word (stop to end): ")
print("Finished")
The first value is read before the loop, so that the first test has something to look at.
Inside the block, use the value first. The next read is the last line of the block.
word=input("Word (stop to end): ")whileword!="stop":
print(word.upper())word=input("Word (stop to end): ")print("Finished")
The value is read in two places: once before the loop, and once as the last line of the block. That way the sentinel is tested before it can be used.
13.7 Leaving early: break
break ends the loop immediately. The rest of the block is skipped, the condition is not tested again, and the program continues with the first line after the loop.
number=1whilenumber<=100:
ifnumber*number>200:
breaknumber+=1print("The first number whose square is above 200:",number)
Output
The first number whose square is above 200: 15
The condition allows up to 100 passes, but the loop stops as soon as it has found its answer. break almost always sits inside an if, because you want to leave only when something particular happens.
while True with break
Combine an endless loop with break and the sentinel loop needs only oneinput line:
largest=0whileTrue:
number=int(input("A positive number (0 to stop): "))ifnumber==0:
breakifnumber>largest:
largest=numberprint("Largest:",largest)
Output
A positive number (0 to stop): 12
A positive number (0 to stop): 45
A positive number (0 to stop): 7
A positive number (0 to stop): 0
Largest: 45
Read it as: for ever: get a number; if it is the sentinel, leave; otherwise use it. The exit test sits in the middle of the block, exactly where the decision is naturally made. This "loop and a half" is the standard Python way to write a loop whose stopping test belongs in the middle.
Asking until the answer is valid
This is the pattern promised in Chapters 6 and 10: keep asking until the user gives something usable. It combines while True, try/except and break:
whileTrue:
reply=input("How many tickets? ")try:
tickets=int(reply)exceptValueError:
print("Please type a whole number.")continueiftickets<=0:
print("Please type a number above zero.")continuebreakprint(f"Booking {tickets} tickets.")
Output
How many tickets? lots
Please type a whole number.
How many tickets? -3
Please type a number above zero.
How many tickets? 4
Booking 4 tickets.
Each problem prints a message and goes round again (continue, explained next). Only a value that survives every check reaches the break. After the loop, tickets is guaranteed to be a positive whole number, and the rest of the program can rely on that.
The condition allows 50 passes, but break can end the loop sooner.
Find the first number whose product with 7 is above 30. break leaves before the update of that pass.
It prints
5
break ends the loop at once, so number keeps the value it had when the if test became true.
Fill in the blank
The user types points, then done. Fill in the statement that leaves the loop.
total=0whileTrue:
reply=input("Points (done to stop): ")ifreply=="done":
total+=int(reply)print("Total:",total)
With the replies 5 then 8 then done, the finished program prints:
Target
Total: 13
while True never ends by its condition. It must be left from the inside.
Which statement ends the whole loop immediately?
total=0whileTrue:
reply=input("Points (done to stop): ")ifreply=="done":
breaktotal+=int(reply)print("Total:",total)
break jumps to the first line after the loop. It sits before the int() line, so the word done is never converted.
Write code
Ask until valid. Keep asking for a whole number from 1 to 5. When the reply is not a whole number, print Please type a whole number. and ask again. When it is a whole number outside 1 to 5, print Please type a number from 1 to 5. and ask again. When the reply is valid, stop asking and print one last line in this form: You chose 4.
With the replies six then 9 then 4, the program prints the lines below. Your program must print exactly these lines.
Example run
Please type a whole number.
Please type a number from 1 to 5.
You chose 4.
Output
Use the shape from section 13.7: while True:, then try and except ValueError around the int() call.
Each problem prints its message and uses continue. Only a reply that passes both checks reaches the break on the last line of the block.
whileTrue:
reply=input("Choose 1 to 5: ")try:
choice=int(reply)exceptValueError:
print("Please type a whole number.")continueifchoice<1orchoice>5:
print("Please type a number from 1 to 5.")continuebreakprint(f"You chose {choice}.")
After the loop the value is guaranteed to be a whole number from 1 to 5, because no other reply can reach the break.
13.8 Skipping ahead: continue
continue ends the current pass and jumps straight back to the top, where the condition is tested again. The loop itself carries on.
When number is a multiple of 3, continue skips the print for that pass.
break
continue
What it ends
the whole loop
only the current pass
Where the program goes
to the first line after the loop
back to the condition
In everyday words
"I am finished here."
"Skip this one. Next!"
continue is never essential: you can always write if number % 3 != 0: and indent the rest. It is useful when it lets you get the "nothing to do in this case" situations out of the way at the top of the block, so that the main work is not buried inside nested ifs. The ticket example above uses it that way.
break ends the whole loop, so 5 and 6 were never reached. continue ends only the pass for 4.
13.9 Assigning inside the condition: the walrus
Chapter 4 introduced the walrus operator :=, which assigns a value and gives that value back. Its best-known use is the sentinel loop, because it lets you read a value and test it in a single line:
while(word:=input("Word (quit to stop): "))!="quit":
print(f"'{word}' has {len(word)} letters.")print("Goodbye.")
Output
Word (quit to stop): hello
'hello' has 5 letters.
Word (quit to stop): Python
'Python' has 6 letters.
Word (quit to stop): quit
Goodbye.
Read the condition from the inside: ask for a word, name it word, then compare it with "quit". The brackets around word := input(...) are required. Without them, := would capture the result of the whole comparison, True or False, because := has the lowest priority of all.
Here are the three ways to write a sentinel loop, side by side:
Style
Shape
Good when
Priming read
read; while value != stop: ... read again
you want it to be very plain
while True + break
while True: read; if stop: break; ...
there are several checks or exits
Walrus
while (value := read) != stop:
the read-and-test fits neatly on one line
All three are correct. Pick the one that reads most clearly for the job.
Practice 13.9
Fill in the blank
Fill in the operator that gives the reply a name and hands the value on to the comparison.
while(wordinput("Word (quit to stop): "))!="quit":
print(len(word))print("Goodbye.")
With the replies hello then sun then quit, the finished program prints:
Target
5
3
Goodbye.
A plain = is not allowed inside a condition.
It is called the walrus operator: a colon followed by an equals sign.
while(word:=input("Word (quit to stop): "))!="quit":
print(len(word))print("Goodbye.")
:= assigns the reply to word and gives the same value back, so it can be compared with "quit" on the same line.
Fix the bug
This should repeat every word the user types until the word is quit. Now it prints You typed True. Fix it.
With the replies tea then milk then quit, the program prints the lines below. Your program must print exactly these lines.
Example run
You typed tea
You typed milk
Goodbye.
Output
:= has the lowest priority of all operators. What does it capture here: the reply, or the result of the comparison?
Put brackets around the part word := input(...).
while(word:=input("Word (quit to stop): "))!="quit":
print(f"You typed {word}")print("Goodbye.")
Without brackets, the comparison runs first and word gets True or False. With brackets, word gets the reply and the comparison uses it.
13.10 Taking a number apart
A classic use of while: process the digits of a whole number one at a time. The two tools come from Chapter 4:
n % 10 is the last digit of n.
n // 10 is nwith its last digit removed.
Repeat until nothing is left:
number=4729total=0whilenumber>0:
digit=number%10total+=digitnumber=number//10print("Sum of the digits:",total)
Output
Sum of the digits: 22
Pass
number
digit (% 10)
total
number after (// 10)
1
4729
9
9
472
2
472
2
11
47
3
47
7
18
4
4
4
4
22
0
This is a true while problem: you do not know in advance how many digits there are, and you do not need to. The loop runs until the number is used up. Note that the loop destroysnumber (it ends at 0). If you need the original afterwards, keep a copy before the loop.
The same skeleton reverses a number. Build the result by shifting it one place left (* 10) and adding each new digit:
Some loops stop when a calculation reaches a goal. How many years does it take for money to double at 7% interest a year?
balance=1000years=0whilebalance<2000:
balance=balance*1.07years+=1print(f"Doubled after {years} years: {round(balance,2)}")
Output
Doubled after 11 years: 2104.85
And a famous puzzle. Take any positive whole number. If it is even, halve it; if it is odd, multiply by 3 and add 1. Repeat. The Collatz conjecture says you always reach 1 in the end. Nobody has ever proved it, though it has been checked for unimaginably many starting values:
% 10 reads the last digit and // 10 removes it. Printing before removing shows 6, then 8, then 3.
Write code
Largest digit. Ask for a positive whole number. Print one line: its largest digit. Use a loop with % 10 and // 10, with no strings. For 4729 the largest digit is 9.
With the reply 4729, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Largest digit: 9
Output
Combine two patterns: the digit loop from this section and "keeping the best so far" from section 13.5.
Start the best value at 0. On each pass, take the last digit, compare it with the best value, then remove the digit.
The digit loop visits every digit once. An if inside it keeps the largest digit seen so far.
13.11 Off by one
The most common loop bug is running one pass too many or one too few. It is so common it has a name: the off-by-one error.
It comes from two small choices: where the counter starts, and whether the test uses < or <=.
Start
Condition
Values the block sees
Passes
i = 0
i < 5
0, 1, 2, 3, 4
5
i = 1
i <= 5
1, 2, 3, 4, 5
5
i = 0
i <= 5
0, 1, 2, 3, 4, 5
6
i = 1
i < 5
1, 2, 3, 4
4
The first two are the standard forms. "Start at 0, test with <" is the Python habit, because it matches string indexes (Chapter 8). "Start at 1, test with <=" suits counting things for people.
The order of the lines inside the block matters as well:
x slips past 1.0 without ever being equal to it. Two rules keep you safe: count with an integer (as steps does here) and work out the float from it, or test with < so that passing the limit is enough.
The else block of a loop runs only when the loop ends because its condition became false.
This loop is left with break. The last line is not part of the else block.
It prints
tries is 2
The loop is left with break on the second pass, so the else block is skipped. The last line runs in every case.
13.14 Common mistakes
The mistake
What you see
The fix
No update in the block
The loop never ends
Change the loop variable in every pass
The update is not indented
The loop never ends
Indent it so it is inside the block
Loop variable not created first
NameError
Give it a starting value before while
Accumulator created inside the loop
The total keeps resetting
Create it before the loop
< where <= was meant (or the reverse)
One pass too few or too many
Check the first and the last pass
!= with a counter that skips the target
The loop never ends
Use < or >
continue placed before the update
The loop never ends
Update before continue
if where while was meant
The block runs only once
while repeats; if does not
Product accumulator started at 0
The result is always 0
Start a product at 1
Comparing input text with a number sentinel
The loop never stops, because "0" != 0
Convert first, or compare with "0"
A float as an exact counter
The loop never ends
Count with an int, or test with <
Expecting the loop to stop the instant the condition changes
The pass still finishes
The condition is tested only at the top
When a loop will not stop: press Ctrl+C, then add a print of the loop variable as the first line of the block and run again. You will see at once whether it is changing, and in which direction.
Practice 13.14
Fix the bug
This should count down from 3 to 1, one number per line, and then print Go!. Now it prints 3 and then Go!. Fix it.
The program prints the lines below. Your program must print exactly these lines.
Example run
3
2
1
Go!
Output
The start, the condition and the update are all there. How many times does the block run?
One keyword runs its block once. Another keyword goes back and tests the condition again.
n=3whilen>=1:
print(n)n-=1print("Go!")
An if runs its block once and moves on. A while jumps back and tests the condition again after every pass.
13.15 Putting it together
Practice 13.15
Write code
Smallest divisor. Ask for a whole number above 1. Print one line: the smallest number above 1 that divides it exactly. For 91 that is 7. For 13 it is 13 itself, because no smaller number divides it. Leave the loop with break as soon as you find a divisor.
With the reply 91, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Smallest divisor: 7
Output
Try the candidates 2, 3, 4 and so on. number % divisor == 0 means that the candidate divides the number exactly.
Use break inside the if. When no candidate below the number divides it, the loop ends by its condition and the candidate is equal to the number.
The loop can end in two ways: break when a divisor is found, or the condition when the candidate reaches the number. In both cases the candidate holds the result.
13.16 How a loop works inside Python
+ Practice
Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.
Questions
Check yourself
What is the one difference between how an if and a while are carried out?
Show the answer
After the block of an if, the program continues downwards. After the block of a while, the program jumps back and tests the condition again.
Check yourself
Name the three ingredients of a counting loop. What happens if the third is missing?
Show the answer
A start (the first value of the loop variable), a condition, and an update. Without the update the condition never becomes false, so the loop is infinite.
Check yourself
When exactly is the condition of a while loop tested?
Show the answer
Once before each pass, at the top. Never in the middle of the block.
Check yourself
Can the block of a while loop run zero times? Give an example.
Show the answer
Yes: if the condition is false the very first time. For example n = 0 and while n > 0:.
Check yourself
After i = 0 and a loop while i < 4: i += 1, what is the value of i? Why is it not 3?
Show the answer
4. The loop continues while i < 4, so it can only end when i is no longer below 4.
Check yourself
Why must an accumulator be created before the loop and not inside it?
Show the answer
Lines inside the loop run on every pass. Creating the accumulator there would reset it each time.
Check yourself
What is the difference between break and continue?
Show the answer
break ends the whole loop. continue ends only the current pass and goes back to test the condition.
Check yourself
Why can continue cause an infinite while loop? How do you avoid it?
Show the answer
continue skips the rest of the block. If the update is in that skipped part, the loop variable never changes. Put the update before the continue.
Check yourself
What is a sentinel? Why must it not be a possible data value?
Show the answer
A special value that signals "stop". If it could also be real data, the loop would stop early when that data was entered.
Check yourself
Why is while x != 1.0: dangerous when x goes up in steps of 0.1?
Show the answer
Floats are approximate, so repeated additions of 0.1 never give exactly 1.0. x passes the target without ever equalling it, and the loop never ends.
Average of many. Keep asking for numbers until the user presses Enter on an empty line. Then print how many numbers were entered and their average. Do not crash if no numbers were entered.
Print how many numbers were entered first, then the average. Your messages should not contain other numbers.
With the replies 4 then 9 then 5 then , the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
3 numbers, average 6.0
Output
You need two things that grow: a total and a count. An empty reply is the sentinel.
Use while True: and test the reply before you convert it: an empty string is falsy, and float("") would crash. After the loop, divide only when the count is not zero.
total=0count=0whileTrue:
reply=input("Number (Enter to finish): ")ifnotreply:
breaktotal+=float(reply)count+=1ifcount:
print(f"{count} numbers, average {total/count}")else:
print("No numbers were entered.")
An empty reply is falsy, so if not reply: detects the empty line. The final if guards against dividing by zero.
total=0count=0whileTrue:
reply=input("Number (Enter to finish): ")ifnotreply:
breaktotal+=float(reply)count+=1ifcount:
print(f"{count} numbers, average {total/count}")else:
print("No numbers were entered.")
Output
Number (Enter to finish): 4
Number (Enter to finish): 9
Number (Enter to finish): 5.5
Number (Enter to finish):
3 numbers, average 6.166666666666667
Write code · Medium
Count the digits. Ask for a positive whole number and print how many digits it has, using a loop with // and not len(str(...)).
With the reply 90210, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Digits: 5
Output
n // 10 removes the last digit. How many times can you do that before nothing is left?
Count one for every pass of a loop that runs while the number is above 0.
Password with three attempts. Ask for a password up to three times. Print Welcome and stop asking as soon as it is correct. After three wrong attempts, print Account locked.
Use the password panda. Print Wrong password. after each wrong attempt. The last line is Welcome or Account locked.
With the replies tiger then lion then panda, the program prints the lines below. Your program must print exactly these lines.
Example run
Wrong password.
Wrong password.
Welcome
Output
Count the attempts. The loop keeps going while fewer than three have been used, and break leaves it on success.
After the loop you must know why it ended. Keep a Boolean flag that starts as False and becomes True just before the break.
Greatest common divisor. The largest number that divides two whole numbers exactly can be found with a method that is over 2000 years old, Euclid's algorithm: as long as the second number is not zero, replace the pair (first, second) with (second, first % second). When the second number is zero, the first is the answer. Ask for two positive whole numbers and print their greatest common divisor. Test with 48 and 18, which should give 6.
With the replies 48 then 18, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
Greatest common divisor: 6
Output
The condition comes straight from the text: keep going while the second number is not zero.
Both numbers change together. Multiple assignment from Chapter 3 does it in one line: first, second = second, ....
first=int(input("First number: "))second=int(input("Second number: "))whilesecond!=0:
first,second=second,first%secondprint("Greatest common divisor:",first)
Multiple assignment from Chapter 3 replaces both numbers at once, using their old values.
first=int(input("First number: "))second=int(input("Second number: "))whilesecond!=0:
first,second=second,first%secondprint("Greatest common divisor:",first)
Output
First number: 48
Second number: 18
Greatest common divisor: 6
Pass
first
second
first % second
1
48
18
12
2
18
12
6
3
12
6
0
—
6
0
the loop ends
Write code · Hard
Is it a palindrome number?. Ask for a positive whole number and print whether it reads the same backwards, such as 12321, by reversing it with arithmetic (no strings).
Print True when the number reads the same backwards and False when it does not.
With the reply 12321, the program prints the lines below. Your program must print exactly these lines.
Example run
True
Output
Section 13.10 shows how to reverse a number with * 10, % 10 and // 10.
The loop uses the number up, so keep a copy of the original first. Compare the reversed number with that copy.
A calculator that keeps going. Take the command calculator from Chapter 12 and put it in a loop, so that it handles one command after another until the user types quit. Support at least add, sub, mul and div. A command that cannot be understood, including one with something that is not a number, should print a message and not end the program. Print how many calculations were done at the end.
Print each result on its own line. Your messages should not contain digits. Print the number of calculations last.
With the replies mul 6 7 then sub 10 4 then fly then div 1 0 then mul 2 two then quit, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.
Example run
42.0
6.0
Commands: add, sub, mul, div (two numbers), quit
Cannot divide by zero.
Those are not both numbers.
Goodbye. Calculations done: 2
Output
The loop is a sentinel loop with quit as the sentinel. A counter that starts at 0 goes up only after a successful calculation.
Put the try inside the loop. Each problem prints a message and uses continue, so that only good commands reach the lines that print the result and add 1 to the counter.
done=0while(line:=input("> ").strip().lower())!="quit":
try:
matchline.split():
case["add",x,y]:
result=float(x)+float(y)case["sub",x,y]:
result=float(x)-float(y)case["mul",x,y]:
result=float(x)*float(y)case["div",x,y]:
result=float(x)/float(y)case_:
print("Commands: add, sub, mul, div (two numbers), quit")continueexceptValueError:
print("Those are not both numbers.")continueexceptZeroDivisionError:
print("Cannot divide by zero.")continueprint(result)done+=1print(f"Goodbye. Calculations done: {done}")
The try is inside the loop, so one bad command prints a message and the loop carries on.
done=0while(line:=input("> ").strip().lower())!="quit":
try:
matchline.split():
case["add",x,y]:
result=float(x)+float(y)case["sub",x,y]:
result=float(x)-float(y)case["mul",x,y]:
result=float(x)*float(y)case["div",x,y]:
result=float(x)/float(y)case_:
print("Commands: add, sub, mul, div (two numbers), quit")continueexceptValueError:
print("Those are not both numbers.")continueexceptZeroDivisionError:
print("Cannot divide by zero.")continueprint(result)done+=1print(f"Goodbye. Calculations done: {done}")
Output
> add 3 4
7.0
> mul 6 7
42.0
> div 1 0
Cannot divide by zero.
> add 3 apple
Those are not both numbers.
> fly
Commands: add, sub, mul, div (two numbers), quit
> quit
Goodbye. Calculations done: 2
Each problem ends its pass with continue, so only successful calculations reach the last two lines of the block. The loop cannot get stuck, because every pass begins by waiting for new input.
Chapter project: Savings goal
Project
Save up for a goal. Write a program that follows deposits until a savings goal is reached. All amounts are whole dollars.
Ask for the goal. Keep asking until the reply is a whole number above zero. For every other reply, print Please type a whole number above zero.
Then ask for deposits, one per pass, as long as the money saved is below the goal.
The reply stop ends the loop early.
A reply that is not made of digits only, or the reply 0, prints Not counted. and the loop goes round again.
A good deposit is added to the money saved, and the program prints a line in this form: Saved 35 of 50
After the loop, print the number of good deposits in this form: Deposits: 2
The last line is Goal reached! when the money saved is equal to the goal or above it. If not, it has this form: Still needed: 15
Plan before you write: which loop is "ask until valid", and which one has two ways to end?
With the replies ten then -5 then 30 then 10 then lots then 0 then 25, the program prints the lines below. Your program must print exactly these lines.
Example run
Please type a whole number above zero.
Please type a whole number above zero.
Saved 10 of 30
Not counted.
Not counted.
Saved 35 of 30
Deposits: 2
Goal reached!
Output
The goal uses the pattern from section 13.7: while True:, a try around int(), continue for each problem and break on the last line of the block.
The deposit loop has the condition saved < goal. Inside it, test for stop first (break), then for a reply that does not count (continue), and only then add the deposit and count it.
After the loop, you do not need a flag: comparing the money saved with the goal tells you which way the loop ended.
whileTrue:
try:
goal=int(input("Goal in dollars: "))exceptValueError:
print("Please type a whole number above zero.")continueifgoal<=0:
print("Please type a whole number above zero.")continuebreaksaved=0deposits=0whilesaved<goal:
reply=input("Deposit (stop to end): ")ifreply=="stop":
breakifnotreply.isdigit()orint(reply)==0:
print("Not counted.")continuesaved+=int(reply)deposits+=1print(f"Saved {saved} of {goal}")print(f"Deposits: {deposits}")ifsaved>=goal:
print("Goal reached!")else:
print(f"Still needed: {goal-saved}")
The program joins two loop shapes from this chapter: "ask until valid" for the goal, and a loop with a condition, a break for the sentinel and a continue for replies that do not count. The update comes after the continue on purpose, which is safe because every pass waits for new input.