Handling Errors
Handling Bad Input
- You should already know
- The guessing game from Loops; writing a function that returns a value (chapter 9).
- You'll build
- A guessing game that survives any answer, using a question-asking function you can reuse.
- You'll be able to
- Catch an expected error with try and except, ask again in a loop, wrap that in a function, and raise an error from your own function.
- You need
- This page. Python runs in the panel beside it; installing Python on your own computer comes in chapter 17.
Play the guessing game from Loops and type seven instead of 7. The game stops with a ValueError. Press Enter without typing anything, and the same thing happens.
You've been told twice that we'd fix this later. Now is later.
We can't stop people typing words. What we can do is tell Python what to do when it happens: say something friendly and ask again. That's called handling an error.
Three code boxes on this page are challenges. Python checks each one when you click Run, as it did in Loops.
What Went Wrong?
Open the Python panel and try int() on some text:
>>> int('7') 7 >>> int('-3') -3 >>> int(' 12 ') 12
int() is happy with digits, a minus sign, and spaces around the number. Now type int('seven'). Python stops with this last line:
ValueError: invalid literal for int() with base 10: 'seven'
int() couldn't do its job, so it gave up and reported a ValueError: a value of the right type (a string) that it can't use. Try int('') and int('7.5') too. Each one is a ValueError.
When something like this happens, programmers say the function raises an error. Up to now, a raised error has always stopped the program. In the panel, it only stopped that one line, and the panel waits for the next. In a program, Python stops at the line that raised the error and doesn't run anything after it.
Try It and See
Python lets us say: try these instructions, and if they raise a ValueError, do this instead.
# Try it: Run it twice. Answer 12 the first time and twelve the # second. Which lines run each time? # Each Run starts fresh. try: age = int(input("How old are you? ")) print(f"Next year you'll be {age + 1}.") except ValueError: print("Please type your age in digits, like 12.") print("Thanks!")
The indented lines under try: run as usual. If none of them raises an error, Python skips the except block and carries on after it.
If a line inside try raises a ValueError, Python stops running the try block straight away. It doesn't print "Next year you'll be". It jumps to the except ValueError: block, runs that, then carries on after it. Either way, Thanks! prints. The program didn't crash.
except ValueError: only catches a ValueError. Any other kind of error still stops the program, just as before. We'll see why that's a good thing shortly.
Ask Again
Printing a polite message is better than a crash, but the program still finishes without an age. What we really want is to ask again until we get a number.
You already know how to repeat a question until the answer is right: while True: and break.
# Try it: Answer twelve, then press Enter with nothing typed, then # answer 12. Then move break out of the try, so it's the last line # inside the loop. Predict what twelve does now, then run it again. # Each Run starts fresh. while True: try: age = int(input("How old are you? ")) break except ValueError: print("Please type your age in digits, like 12.") print(f"Next year you'll be {age + 1}.") print("Thanks!")
break sits inside try, just after int(). Python only reaches it when int() succeeded. If int() raises an error, Python jumps over break to the except block, prints the message, and goes round the loop to ask again.
When the loop does end, age is always a number, so the lines after the loop are safe.
If you moved break out of the try, it ran after every answer, good or bad. twelve printed the message, then left the loop without an age, and the line after the loop stopped with a NameError. Put break back inside the try.
Catch Only What You Expect
You might wonder why we write except ValueError: and not just except:. Python does allow a bare except:, which catches every kind of error. It sounds safer. It isn't.
Suppose you made a typo inside the try:
while True: try: age = int(inptu("How old are you? ")) break except: print("Please type your age in digits, like 12.")
inptu is a NameError, not a problem with the player's answer. A bare except: catches it anyway. The program never asks the question. It prints "Please type your age in digits" over and over, forever, and the real problem is hidden.
With except ValueError:, the typo stops the program at once with a NameError that names the mistake. Catch the error you expect, and let Python tell you about the rest.
Wrap It in a Function
Every game that asks for a number needs this loop. In Functions, you learned to write instructions once, give them a name, and call them whenever you need them.
# Try it: Answer a word or nothing to each question before giving a # number. Then add a third question of your own, using ask_number(). # Each Run starts fresh. def ask_number(question): while True: try: return int(input(question)) except ValueError: print("Please type a whole number, like 12.") age = ask_number("How old are you? ") pets = ask_number("How many pets do you have? ") print(f"Next year you'll be {age + 1}.") print(f"That's {pets} pets to feed.")
The question is a parameter, so each call can ask something different. The function returns the number, and the caller decides what to do with it.
There's no break this time. return ends the function call immediately, as you saw in Functions, and that ends the loop too. Python only reaches return once int() has produced a number.
Fix the Guessing Game
Here's the random guessing game from Loops, with ask_number() added at the top. The game doesn't use it yet, so it still crashes on seven.
# Change the game so it asks for each guess with ask_number(). # Check it: type seven, then keep guessing. # Each Run starts fresh. import random def ask_number(question): while True: try: return int(input(question)) except ValueError: print("Please type a whole number, like 7.") secret = random.randint(1, 10) print("I'm thinking of a number from 1 to 10.") while True: guess = int(input("What's your guess? ")) if guess < secret: print("Too low!") elif guess > secret: print("Too high!") else: print("You got it!") break print("Thanks for playing.")
Change one line, and the game can't be crashed by a typo any more. The function hides the loop and the try; the game just asks for a number and gets one.
Raise Your Own Error
So far, int() has raised the errors and we've caught them. Our own functions can raise errors too.
In Functions, you wrote a ticket calculator: visitors older than 11 pay 5, and younger visitors get in free. Here's a function for one visitor. What should it do with an age of -4?
# Try it: Run it and read the last line of the error. Then change # -4 to 4. # Each Run starts fresh. def ticket_price(age): if age < 0: raise ValueError("An age can't be negative.") if age > 11: return 5 return 0 print(ticket_price(30)) print(ticket_price(8)) print(ticket_price(-4))
raise stops the function and reports an error, just as int('seven') did. We choose the kind of error and write the message. ValueError fits: the age is a number, but not a value that makes sense.
Without the raise, -4 would fall through to return 0. The function would quietly hand out a free ticket, and the mistake would travel on through the program. A function that can't give a sensible answer should say so.
Raising doesn't decide what happens next. The caller decides, and it can catch the error with the same try and except you used for int():
# Try it: Add another age to the list, such as -1 or 11. # Each Run starts fresh. def ticket_price(age): if age < 0: raise ValueError("An age can't be negative.") if age > 11: return 5 return 0 for age in [30, -4, 8]: try: print(f"Age {age}: {ticket_price(age)}") except ValueError as error: print(f"Age {age}: no ticket. {error}")
as error gives the caught error a name, so we can print its message. Here, that's the message we wrote in ticket_price(). Notice that one bad age didn't stop the loop: the try is inside it, so each age gets its own try.
You'll see raise ValueError(...) and except ... as error again in later chapters, wherever a function needs to refuse a value that makes no sense.
Your Turn
Predict
# Before you run this, write down what you think it will print. # Each Run starts fresh. # Write your prediction below before running. # After the first run, edit the code and predict again. for answer in ['12', 'twelve', '7']: try: number = int(answer) print('Got', number) except ValueError: print('Skipped', answer) print('Done')
When int('twelve') raises its error, which line inside try doesn't run?
Find the Bug
This program should keep asking until it gets a number, but ten still crashes it. Run it, answer ten, and read the last line of the error.
# Run it and answer ten. Then fix one line. # Each Run starts fresh. def ask_number(question): while True: try: return int(input(question)) except TypeError: print("Please type a whole number, like 3.") pizzas = ask_number("How many pizzas? ") print(f"{pizzas} pizzas, coming up.")
On Your Own: A Number in Range
ask_number() will accept 0 or 50 as a guess in a game from 1 to 10. Write ask_number_between(question, low, high), which keeps asking until the answer is a whole number from low to high, both included, and then returns it.
# Write ask_number_between() and use it for the guess below. Check: # eleven, 0 and 11 should each get a message, and 4 should be # accepted. Then check that 1 and 10 are accepted on the first try. # Each Run starts fresh. def ask_number(question): while True: try: return int(input(question)) except ValueError: print("Please type a whole number, like 7.") guess = ask_number("Pick a number from 1 to 10: ") print(f"You picked {guess}.")
Hint: Where do you start?
Your new function can call ask_number(). That takes care of words and empty answers, so all your function has to check is whether the number is in range. Return it if it is; otherwise, print a message and let the loop ask again.
When it works, put it into your guessing game, with 1 and 10 as the range.
In Your Own Words
Write one sentence explaining what Python does when a line inside try raises a ValueError. Include which lines it skips and where it carries on.
What's Next?
Your guessing game now survives anything a player types. You can catch an error you expect, ask again, keep that pattern in a function, and raise an error when your own function is given something that makes no sense.
In The Word-Prediction Generator, we'll combine lists, dictionaries, loops and functions to make something stranger: a program that writes new text from Shakespeare.