On Sat, Apr 23, 2011 at 6:38 PM, Alan Gauld <alan.ga...@btinternet.com> wrote: > > "Rance Hall" <ran...@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... >
I knew about len, but somehow didnt think of it in this context. I didn't know that the last iteration of i and option would still be around. Some loops like that in some languages sort of clean up after themselves. 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: menuchoice = int(input('\nYour Choice? ')) if menuchoice >= 1 and menuchoice <= i: return menuchoice-1 else: print("Entry not valid") Maybe the while not loop could have been avoided, but it made sense to me, and was consitent with a pattern I used in another section of code. 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. So I *think* that I should strip out the int() from the input line and let the input stand on its own. Then as part of the if logic block at a test to see IF a int type conversion would succeed. If so, do it and make sure it is within the range. If no type conversion can happen, then reask the question just as we do if the number is not in the desired range. This was the part I was stuck on. I just didnt know it till I finished this much and still wasn't happy with the results for me to put a finger on exactly what my problem was. Thanks again all. Rance _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor