[Tutor] Most pythonic input validation
robert.johansson at math.umu.se
Fri Oct 16 13:25:08 CEST 2009
> I'm writing a text based menu and want to validate the user input. I'm
> giving the options as integers, and I want to make sure the user enters a
> proper value.
> Here's what I've got so far: http://pastebin.com/m1fdd5863
> I'm most interested in this segment:
> while True:
> choice = raw_input(prompt)
> if valid_choice(choice, 0, len(options)-1):
> return choice
> Is that the most pythonic way of validating? Is there a better way?
> As an aside, in the valid_choice function I know I could do:
> if not choice in range(min, max)
> but I figured a comparison would probably be the better choice, correct?
> To be considered stupid and to be told so is more painful than being
> gluttonous, mendacious, violent, lascivious, lazy, cowardly: every
> every vice, has found its defenders, its rhetoric, its ennoblement and
> exaltation, but stupidity hasnt. - Primo Levi
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
The most pythonic way would be to use a try except block:
choice = raw_input(prompt)
except (KeyError, IndexError, TypeError):
print "Invalid input, try again."
Also, did you want to convert choice to an int at some point? You
appear to be comparing it to a number in valid_choice(), but it will
be passed out of the method as a str.
Hence I've added a conversion to int, and I'm catching KeyError (for
dicts), IndexError (for lists), and TypeError, for when int(choice)
This is a principle called "It's Easier to Ask Forgiveness than
Permission" (EAFP), which is one of the pythonic principles.
Hope that helps.
Rich "Roadie Rich" Lovely
What if a valid user input has to be an integer between 10 and 20? I mean,
it could be that you are doing something that only makes sense for that
input. Would it be pythonic to add a test like:
If prompt in range(10,21):
... raise an error
If I understand the error handling correctly you can add your own user
defined error, but is that really what you should do in that case?
More information about the Tutor