Python: Unable to quit menu - user input -


i need define function 'menu' user able enter number based on choices. here have far:

def menu(preamble, choices) :     choose_one = " choose 1 of following , enter number:"     print(preamble + choose_one)      number in range(len(choices)):         = "%g: %s" % (number + 1, choices[number])         print(all)      prompt = ("\n")       warning = "\n"         while warning:         choose = int(input(warning + prompt))         warning = ''         if choose not in range(1,len(choices)):             warning = "invalid response '%s': try again" % choose             number in range(len(choices)):                 = "%g: %s" % (number + 1, choices[number])                 print(all)                     else:             break     return choose 

let's say, example choices are:

1. have brown hair 2. have red hair 3. quit 

i've tried running code , works fine when choose == 1 , choose == 2. when choose == 3, ask user pick again. need option "quit" work?

you need add 1:

len(choices) + 1 

ranges half open upper bound not included 3 not in range if length 3.

in [12]: l = [1,2,3]  in [13]: list(range(1, len(l))) out[13]: [1, 2]  in [14]: list(range(1, len(l) + 1)) out[14]: [1, 2, 3] 

i change logic bit:

st = set(range(1, len(choices))+ 1) while true:     choose = int(input(warning + prompt))     if choose in st:         return choose     print("invalid response '%s': try again" % choose)     number in range(1, len(choices)  + 1):         msg = "%g: %s" % (number, choices[number])         print(msg)     

you use dict store choice , number:

from collections import ordereddict choices  = ordereddict(zip(range(1, len(choices)+ 1),choices)) k,v in choices.items():         msg = "%g: %s" % (k, v)         print(msg)  while true:     choose = int(input(warning + prompt))     if choose in choices:         return choose     print("invalid response '%s': try again" % choose)     k,v in choices.items():         msg = "%g: %s" % (k, v)         print(msg) 

Comments