[Tutor] Most pythonic input validation

Wayne Werner waynejwerner at gmail.com
Thu Oct 15 16:36:47 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 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091015/6d86d9bd/attachment.htm>

More information about the Tutor mailing list