Python: 无法退出菜单 - 用户输入

Python: Unable to quit menu - user input

我需要定义一个函数 'menu' 以便用户能够根据选择输入数字。这是我目前所拥有的:

def menu(preamble, choices) :
    choose_one = " Choose one of the following and enter its number:"
    print(preamble + choose_one)

    for number in range(len(choices)):
        all = "%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
            for number in range(len(choices)):
                all = "%g: %s" % (number + 1, choices[number])
                print(all)            
        else:
            break
    return choose

比方说,选项是:

1. I have brown hair
2. I have red hair
3. Quit

我试过 运行 代码,当 choose == 1 和 choose == 2 时它工作正常。但是当 choose == 3 时,它会要求用户重新选择。我需要做什么才能使选项 "Quit" 起作用?

你需要加1:

len(choices) + 1

范围是半开,所以不包括上限,所以如果长度为 3,则 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]

我还要稍微改变一下你的逻辑:

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)
    for number in range(1, len(choices)  + 1):
        msg = "%g: %s" % (number, choices[number])
        print(msg)    

您还可以使用字典来存储选择和数字:

from collections import OrderedDict
choices  = OrderedDict(zip(range(1, len(choices)+ 1),choices))
for 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)
    for k,v in choices.items():
        msg = "%g: %s" % (k, v)
        print(msg)