[Tutor] validating user input

Alan Gauld alan.gauld at btinternet.com
Sun Apr 24 01:38:20 CEST 2011


"Rance Hall" <ranceh at gmail.com> wrote

> Ok, so I have this code that is working, but does little to validate
> user input and I don't quite yet understand that process yet.
>
> so given the following function:
>
> def buildmenu(menuchoices):
>    for i, option in enumerate(menuchoices, 1):

Interesting, I didn't know enumerate could take a second
argument, and help() doesn't mention it eioither.... You
learn something new ...

>        print('%s. %s' % (i, option))
>    menuchoice = int(input('\nYour Choice? '))
>    return menuchoice-1
>
> I need help understanding how exactly we validate the input since in
> this case I have no idea how many menu entries there would be.

But you have just finished enumerating them and I holds
the index of the last item, or in your case the count of
the last item. But even without that you can always
use len() to find out how many menuchoices there are...


So you can check if choice lies between 1 and
len(menuchoices) or between 1 and i whichever
you prefer.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list