[Tutor] Most pythonic input validation
Rich Lovely
roadierich at googlemail.com
Thu Oct 15 18:17:16 CEST 2009
2009/10/15 Wayne Werner <waynejwerner at gmail.com>:
>
>
> On Thu, Oct 15, 2009 at 10:50 AM, Rich Lovely <roadierich at googlemail.com>
> wrote:
>>
>> 2009/10/15 Wayne Werner <waynejwerner at gmail.com>:
>> > Hi,
>> > 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):
>> > break
>> > 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?
>> > Thanks,
>> > Wayne
>> > --
>> > 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:
>> > http://mail.python.org/mailman/listinfo/tutor
>> >
>> >
>>
>> The most pythonic way would be to use a try except block:
>>
>> while True:
>> choice = raw_input(prompt)
>> try:
>> options[int(choice)]
>> except (KeyError, IndexError, TypeError):
>> print "Invalid input, try again."
>> continue
>> return choice
>
> Ah, that's much cleaner, I like it :)
> yeah, I noticed right after I had sent my email that I forgot to convert it
> to an int. Though I do believe (and checking confirms) it's ValueError on an
> int() fail:
> ValueError: invalid literal for int() with base 10: 'asdf'
> Now I can eliminate a function, so that's helpful :)
> Thanks,
> Wayne
Ah yes, should probably have checked that myself... I added that
before the conversion to int, and trying to index a list with a string
raises TypeError...
--
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
mailing list