Jericho Jones Jericho Jones - 3 months ago 7
Python Question

Python 2.7: Handling wrong input which is not a string

I am writing a program which is supposed to contain a way of informing the user that the input for one of the variables is not a string, if entered as a name by user.

E.g. program expects a user input of any string, and if it is a string which is contained within dictionary, it will print out its value, if not, it will print out an error message.

ageofdeath.getage('JesusChrist')

33

ageofdeath.getage('John McCena')


This is not a bible character. Please enter a name of a character from the bible.

but, the program should at least throw an error message when confronted with wrong user input such as

ageofdeat.getage(JesusChrist)


ideally popping up a message along the lines of "This is not a string please input a string". Instead, no matter whether i try to use
if
=
or isinstance, it always shows typical python name is not defined error. Is there a way of going round this or not really, as it is a default way of python shell handling the input?

Answer

Your program isn't even getting to the part where it executes your getage() method. It is failing far earlier.

You're using input() instead of raw_input(). Thus JesusChrist is taken as the name of a variable because input() evaluates what the user types as a Python expression. JesusChrist is a legal Python variable name, it just hasn't been defined, so Python tells you that. And because it knows you can't do anything with a value that doesn't exist, it stops.

Now you could catch that error by wrapping your input() in a try/except block, but that's just trying to compensate for making the wrong decision in the first place. The right answer is to use raw_input() to get input from your user and it will always be a string.

Comments