Handling Errors
00:00 In the previous lesson, I showed you how to convert data types and why you need to do that if you want a number as a result of user input. In this lesson, I’ll show you what to do if the user ignores your instructions to type in a number.
00:13
So far, when converting strings to numbers, I’ve been using strings that actually contain numbers, but that doesn’t have to be the case. A user could type any old thing, even xyz when you ask for a number. If you call the int() or float() constructors with a value that cannot be converted, the constructor raises an exception.
00:33
This sample code demonstrates the result. A string containing the word thirty-five is easy enough to understand as a human, but Python does not know what to do with that.
00:44
The int() constructor raises a ValueError exception telling you invalid literal for int() with base 10. That message is a little cryptic.
00:53
A literal is a general term for a specific type of data. A string literal is one possible choice. That’s why the message starts with the phrase invalid literal. The int() constructor supports arbitrary bases, so you can convert using base 10 or something else like binary or hexadecimal, which are base 2 and 16, respectively.
01:14
By default, the int() constructor uses base 10. The error here is actually being helpful because ab is a valid base 16 number, but not a valid base 10.
01:25 So some characters work and some don’t, depending on the base. That exception is tricky enough for a programmer to understand, but your users might not be programmers.
01:35
You may want an easier-to-understand message if their input is invalid. You can do that in your code by catching the Value Error exception, then printing your own error, then prompt them again until they give you something that works.
01:49 Let me show you a program that does just that.
01:53
I’ve written a short program in a file called int_input.py. As a quick aside, you should never name a program a valid Python function or module name.
02:02
At best, it is confusing. At worst, it can muck with your imports. So calling this int.py or input.py would be problematic.
02:11 I start the program with an infinite loop. I want to keep prompting the user until they give me something valid, so I’m going to loop forever and then break out of the loop when they get it right.
02:22
As I mentioned before, the goal here is to catch any exceptions. The try/except block is how you do that. If an exception happens within the try portion, the except may get triggered.
02:33
I say “may” because in this case I’m explicitly catching Value Error exceptions. The except block only gets run if that exact exception type is thrown.
02:43
If an AttributeError got thrown instead, the program would exit, showing you the exception. The ValueError is what I’m interested in, though, so this is going to catch what I want it to.
02:54
Inside of the try block, I prompt the user for input and call the int() constructor inline, hopefully storing the result in the age variable.
03:02
Let’s deal with the negative case first. If the int() constructor can’t convert what the user types into an integer, it throws a ValueError that will get caught here.
03:12
And in the catching block, I’m printing out an error message to the screen in simpler English than used by the exception itself. The next line is the bottom of the while loop.
03:23
So after the print(), you loop back up to the top again. Since True is always true, back into the loop you go. Here, I’m back at the input() call.
03:33
This time, let’s say the conversion succeeds. The block then continues, printing out a message. My message uses an f-string to display the value of age + 1.
03:43
You can do simple operations within brace brackets like you might do in a REPL or in your code. If you needed the value of age + 1 somewhere else, you might keep it in a variable, but since I only want to print it, I’m using the f-string way instead.
03:58
Since I got a result from input() that I liked, the last thing I do here is call break. That breaks out of the loop. As there is nothing after the loop, this break statement will cause the execution to hit the bottom of the script, closing the program. Let me open up a shell, and I’ll try this out.
04:15 Running the program, answering the prompt.
04:20
six is a bad number, and there is the error message and a new version of the prompt. Note how this time around the prompt isn’t colorized. That’s because colorization is a service provided by the REPL, and here I’m running a script, not the REPL. Let me type in something valid, and there is the result, and the program ends.
04:43 So far, I’ve only been asking the user for a single response. In the next lesson, I’ll show you how to deal with multiple values at a time.
Become a Member to join the conversation.
