livepython.net
CHAPTER 11While Loops
11.3  INPUT LOOPS

Python Input Loops: Keep Asking Until It's Right

Keep Asking Until the Answer Is Valid

An input loop is a while loop that calls input() again and again. Its first job: keep asking until the user gives a valid answer, instead of stopping at the first mistake.

In chapter 8, an if could only complain about bad input once. A while can ask again:

PYTHONedit me
marks = int(input())
while marks < 0 or marks > 100:
    print("Marks must be 0 to 100. Try again.")
    marks = int(input())
print("Saved:", marks)
OUTPUT
Marks must be 0 to 100. Try again.
Marks must be 0 to 100. Try again.
Saved: 80

The Input box has three lines, one for each input() call: 150 and -5 fail the check, and 80 passes. Change the lines and run it again.

Think of a shop assistant who asks your shoe size. Say "99", and they ask again, until you say a size they have.

The pattern

  1. Ask once before the loop.
  2. While the answer is bad: say what's wrong, and ask again inside the loop.
  3. After the loop, the answer is sure to be good.

The input() inside the loop is the loop's change: it's the line that can make the condition False. Leave it out, and you get an endless loop, printing "Try again" forever.

Write the bad case in the condition

The condition describes a bad answer, because that's when the loop should keep going:

You wantThe while condition
a number from 1 to 10while n < 1 or n > 10:
more than 0while n <= 0:
the right PINwhile pin != "1234":

Common beginner doubt: "What if the user types abc?" Then int() stops the program with a ValueError, before the loop can help. Catching that needs try and except, from chapter 17.

Ask once, then while the answer is bad, explain and ask again.

your turnPredict the output

What will this print?

n = int(input()) while n <= 0: print("again") n = int(input()) print("ok", n)

The user types: 0-37

Your turn! What will this code show on the screen?
your turnFill the gap

Keep asking until the PIN is right

pin = input() while pin ? "1234": print("Wrong PIN") pin = input() print("Welcome")

The user types: 11111234

It should print: Wrong PIN Welcome

Which piece makes this code work?

Stop at a Word Like done (Sentinel Value)

How does a program know when the user has finished typing? You agree on a stop word, like done. A special value that means "stop" is called a sentinel value (a sentinel is a guard who keeps watch).

PYTHONedit me
items = []
item = input()
while item != "done":
    items.append(item)
    item = input()
print("You need", len(items), "things:", items)
OUTPUT
You need 3 things: ['milk', 'bread', 'eggs']

Think of a waiter taking your order: they keep writing until you say "That's all".

Two ways to write it

The loop above asks before the loop, and again at the end of each round. The same program with while True and break asks in just one place:

PYTHONedit me
items = []
while True:
    item = input()
    if item == "done":
        break
    items.append(item)
print("You need", len(items), "things:", items)
OUTPUT
You need 3 things: ['milk', 'bread', 'eggs']
StyleGood for
ask before + at the endshort loops; the stop is in the while line, easy to see
while True + breakone input() line only; the stop check sits where the answer arrives

Both are fine. Pick the one you find easier to read.

The stop word is not data

Notice that done never ends up in the list. Check for the stop word before you use the answer.

Avoid: running out of input

Here in LivePython, every input() takes the next line of the Input box. If your loop asks for more lines than there are, Python stops with an error:

PYTHONedit me
item = input()
while item != "done":
    print("Got", item)
    item = input()
OUTPUT
Got milk
EOFError: EOF when reading a line

EOF means "end of file": there was no more input to read. Add the stop word as the last line, and it works.

A stop word ends an input loop. Check for it before you use the answer.

your turnType the output

Type what this prints

count = 0 word = input() while word != "stop": count += 1 word = input() print(count)

The user types: redbluegreenstop

Read the code line by line, then type the output exactly.
your turnOrder the lines

Put the lines in order to add numbers until done

  1. print(total)
  2. total = 0
  3. text = input()
  4. while True:
  5. total += int(text)
  6. break
  7. if text == "done":

The user types: 46done

These lines are mixed up. Put them back in order, then press Check.

Add Up Numbers Until the User Stops

Input loops shine when you add up values and don't know how many there will be. Combine the stop word with a running total and a counter, and you can work out sums and averages of any length.

PYTHONedit me
total = 0
count = 0
n = int(input())
while n != 0:
    total += n
    count += 1
    n = int(input())
print("Total:", total)
if count > 0:
    print(f"Average: {total / count:.2f}")
OUTPUT
Total: 245
Average: 81.67

Here the stop value is the number 0. It's a good sentinel when 0 can't be a real answer, like marks or prices here.

Think of a cashier: they scan items one by one, keeping a running total, until there's nothing left on the belt.

The parts

VariableStarts atEach round
total0total += n adds the new number
count0count += 1 counts one more number

Both start before the loop. Start them inside, and they're reset to 0 every round.

Watch out for an empty list of numbers

What if the very first answer is 0? Then the loop never runs, count stays 0, and total / count would give a ZeroDivisionError. That's why the average sits inside if count > 0:, the check-first habit from chapter 8.

PYTHONedit me
total = 0
count = 0
n = int(input())
while n != 0:
    total += n
    count += 1
    n = int(input())
if count > 0:
    print(f"Average: {total / count:.2f}")
else:
    print("No numbers given")
OUTPUT
No numbers given

Text or number stop?

If 0 could be a real answer (a temperature, a score in a game), use a word like done as in the last lesson: read the text, check for the stop word, and only then use int().

Start the total and the counter before the loop, add each round, and check count before you divide.

your turnPick the right idea

Why is total = 0 written before the loop, not inside it?

Think about it, then pick one.
your turnPredict the output

What will this print?

total = 0 n = int(input()) while n != 0: total += n n = int(input()) print(total)

The user types: 5-240

Your turn! What will this code show on the screen?

Give the User Only a Few Tries

A cash machine doesn't let you guess a PIN forever. To limit the tries, join two conditions with and (chapter 8): keep asking while the answer is wrong and there are tries left.

PYTHONedit me
pin = input()
tries = 1
while pin != "1234" and tries < 3:
    print("Wrong PIN. Try again.")
    pin = input()
    tries += 1
if pin == "1234":
    print("Welcome, Lucky!")
else:
    print("Card blocked.")
OUTPUT
Wrong PIN. Try again.
Wrong PIN. Try again.
Welcome, Lucky!

Now try the Input lines 1, 2 and 3: two "Wrong PIN" messages, then Card blocked.

Think of a game with three lives: you keep playing while you haven't won and you still have lives left.

Two ways out

This loop can end for two reasons:

  • the PIN is right, so pin != "1234" is False, or
  • the tries are used up, so tries < 3 is False.

and needs both sides True to go on, so either one ends the loop.

Find out why it ended

After the loop, you don't know which reason stopped it. Ask with an if, as the example does: if the PIN is right, the user got in; otherwise the tries ran out.

Check the answer, not the counter. On the third try, tries is 3 whether the PIN was right or wrong, so if tries == 3: can't tell you if the user got in.

Count the tries carefully

tries starts at 1, because one answer is already read before the loop. Each new input() adds 1. That's the off-by-one thinking from topic 2: trace the edges, and make sure the user gets exactly 3 tries, not 2 or 4.

Limit the tries with and, then use if after the loop to see why it ended.

your turnPredict the output

What will this print?

pin = input() tries = 1 while pin != "1234" and tries < 3: pin = input() tries += 1 print(tries, pin)

The user types: 55551234

Your turn! What will this code show on the screen?
your turnPredict the output

What will this print?

a = input() b = input() print(a + b)

The user types: 23

Your turn! What will this code show on the screen?

Practice: Input loops

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 95.Python Program to Add Numbers Until the User Types 0EasySolve
  2. 96.Python Program to Ask Again Until the Age Is ValidEasySolve
  3. 97.Python Program to Find the Largest Number Until done Is TypedMediumSolve