By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,172 Members | 762 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,172 IT Pros & Developers. It's quick & easy.

try: except: ValueError

P: n/a
hi

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:

#menuloop
menuChoice = 7
printMenu()
while menuChoice != 0:
try:
menuChoice = int("1 = write | 2 = view | 0 = quit"))
except ValueError:
print "enter a number"

if menuChoice == 1:
writeEntry()
elif menuChoice == 2:
viewEntry()
elife menuChoice == 0:
pass
else:
printMenu()

print "bye"

this works as though I never added try: and except ValueError: at all.
the program just doesn't use them at all.

if a user types a&s it still errors 'a&s' is not defined

what am i doing wrong here?

Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Mike Hoy wrote:
hi

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:

#menuloop
menuChoice = 7
printMenu()
while menuChoice != 0:
try:
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.

Kent
Jul 19 '05 #2

P: n/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.

yes that did it, thanks

Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.