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

时间:2016-03-26 18:41:17

标签: python python-3.5

我需要定义一个功能菜单'使用户能够根据选择输入数字。以下是我到目前为止的情况:

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

我已尝试运行代码,并且在选择== 1并选择== 2时工作正常。但是当选择== 3时,它会要求用户再次选择。选项" Quit"我需要做什么?工作?

1 个答案:

答案 0 :(得分:1)

您需要添加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)    

您还可以使用dict来存储选项和数字:

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)