[Tutor] validating user input
ALAN GAULD
alan.gauld at btinternet.com
Sun Apr 24 10:01:59 CEST 2011
> "Rance Hall" <ranceh at gmail.com> wrote
>
> >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...
>
> I knew about len, but somehow didnt think of it in this context.
>
> So at the present time I have this:
>
> def buildmenu(menuchoices):
> for i, option in enumerate(menuchoices, 1):
> print('%s. %s' % (i, option))
> validdata = False
> while not validdata:
instead of validData you could just use
while True:
since you never change validData anyway and use a
return to break out of the loop.
> menuchoice = int(input('\nYour Choice? '))
> if menuchoice >= 1 and menuchoice <= i:
> return menuchoice-1
> else:
> print("Entry not valid")
You can tidy up the if test slightly:
if ( 1 <= menuchoice <= i):
return menuchoice-1
Also why bother with the minus 1?
You can use the values 1-n just as easily.
> Maybe the while not loop could have been avoided,
No, you need some kind of loop to repeat the choice.
Otherwise you just exit the program with an error,
which seems a bit harsh!
> The issue I have now is that the input might not be an integer at all.
> If it isnt, then the int conversion that is part of the input line
> will die with a fatal error.
No, it will throw a ValueError which you can catch and
handle exactly as you did above
while True
try:
menuchoice = ....
if (...):
else....
except ValueError:
except other errors
HTH,
Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110424/7f8ba489/attachment.html>
More information about the Tutor
mailing list