I have a very basic assignment, but I just simply can not get the right error I am looking for. Here is the assignment:
10-6 Addition: One common problem when prompting for numerical input occurs when people provide text instead of numbers. When you try to convert the input to an int, you'll get a TypeError. Write a program that that prompts for two numbers. Add them together and print the result. Catch the TypeError if either input value is not a number, and print a friendly error message. Test your program by entering two numbers and then by entering some text instead of a number.
Here is what I have:
print("Please enter two numbers and this program will add them together!")
try:
num_1 = int(input("What is your first number?"))
num_2 = int(input("What is your second number?"))
answer = num_1 + num_2
print(str(num_1) + " + " + str(num_2) + " = " + str(answer))
except TypeError:
print("Please make sure you enter a number next time.")
I have rearranged this for like an hour now, and no matter what I do I can't get a TypeError, only a ValueError. How am I able to get a TypeError in this, or is the book just wrong and it is impossible to get a TypeError in this scenario??
3 Answers 3
>>> int('abc')
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
The book is wrong.
3 Comments
input. The OP wrote the code.input won't raise a TypeError for any non-contrived input I can think of, and it would also make the int redundant. And it says "When you try to convert the input to an int, you'll get a TypeError".A TypeError is thrown when trying something like
answer = 2 + '3'
Your exercise is a bit misleading, because such a situation will never happen in a program like the one you are supposed to write. The error you can get when trying to explicitly convert a str to a int is a ValueError, as you say. So yes, catch the ValueError with
except ValueError:
and you are good to go.
Also, you are converting your int back into a str with the line
answer = num_1 + str(num_2)
which is incorrect. You should just do
answer = num_1 + num_2
2 Comments
The book is not wrong. The question didn't actually ask you to convert to int.
Just change to num_1 = input("What is your first number?") and num_2 likewise and your exception handling will be triggered if exactly one of the inputs is a string.
Granted, it's a little confusing because of the line "When you try to convert the input to int, [...]" but nowhere did it ask you to do this conversion explicitly. It was probably just referring to the implicit conversion happening when using + with an integer and a string.
To learn a little more about Python, you could also test what happens if both inputs are a string.
ValueErrorif I am not mistaken.