try: except: ValueError
kent37 at tds.net
Fri Jun 10 19:52:45 CEST 2005
Mike Hoy wrote:
> my goal is to handle the problem of a user typing a letter or symbol
> rather than a number I found something called try: and ValueError:
> Anyway this is what i attempted:
> menuChoice = 7
> while menuChoice != 0:
> menuChoice = int("1 = write | 2 = view | 0 = quit"))
> except ValueError:
> print "enter a number"
presumably you meant menuChoice = input("1 = write | 2 = view | 0 = quit").
input() evaluates the user's input similarly to what the interactive interpreter does, so if you type something like a&s you get a NameError - input() is trying to evaluate the expression 'a&s', it looks for a variable named 'a'.
The solution is to use raw_input() which returns the user input as a string. Then you can do whatever validation you wish, e.g.
menuChoice = int(raw_input("1 = write | 2 = view | 0 = quit"))
which will raise an exception if the input is not a valid integer.
More information about the Python-list