[Tutor] Most pythonic input validation
roadierich at googlemail.com
Thu Oct 15 17:50:57 CEST 2009
2009/10/15 Wayne Werner <waynejwerner at gmail.com>:
> 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 called
> gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness,
> every vice, has found its defenders, its rhetoric, its ennoblement and
> exaltation, but stupidity hasn’t. - 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
There are 10 types of people in the world: those who know binary,
those who do not, and those who are off by one.
More information about the Tutor