允许用户从带有for循环的菜单中选择选项

时间:2014-02-25 18:06:51

标签: python for-loop

我正在开发一个程序的一部分,该程序向用户显示3个选项的菜单。我希望允许用户输入他们的菜单选项(1-3),之后菜单再次出现并允许用户输入另一个选项并重复此过程总共n次,用户也在菜单之前输入。

该程序只是连续3次打印菜单而不是单独的迭代,但我不知道如何解决这个问题。

n = int(input('Please enter the number of iterations:'))

for i in range(0,n):

    print('Enter 1 for choice 1\n')

    print('Enter 2 for choice 2\n')

    print('Enter 3 for choice 3\n')

    choice = int(input('Enter your choice:'))

    if (choice == 1):

    ....
    ....

    else:
        print('Invalid choice')

3 个答案:

答案 0 :(得分:6)

放置代码来处理循环内的选择:

n = int(input('Please enter the number of iterations:'))

for i in range(0,n):

    print('Enter 1 for choice 1\n')

    print('Enter 2 for choice 2\n')

    print('Enter 3 for choice 3\n')

    choice = int(input('Enter your choice:'))

    if (choice == 1):

        ....
        ....

    else:
        print('Invalid choice')

答案 1 :(得分:1)

缩进下面的一段代码,右边有4个空格:

if (choice == 1):
    ...
    ...
else:
    print('Invalid choice')

但是如果我可以建议更好地实现你想要做的事情,那么定义一个可以处理非数字用户输入的函数,另外,将这些打印带到for循环之外:< / p>

def getUserInput(msg):
    while True:
        print msg
        try:
            return int(input(msg))
        except Exception,error:
            print error

n = getUserInput('Please enter the number of iterations:')

print 'Enter 1 for choice 1'
print 'Enter 2 for choice 2'
print 'Enter 3 for choice 3'

while n > 0:
    choice = getUserInput('Enter your choice:')
    if choice == 1:
        ...
        n -= 1
    elif choice == 2:
        ...
        n -= 1
    elif choice == 3:
        ...
        n -= 1
    else:
        print 'Invalid choice'

答案 2 :(得分:1)

只是为了好玩:我已经重写了这一点,以介绍一些更高级的想法(程序结构,使用enumerate(),一流的功能等)。

# assumes Python 3.x
from collections import namedtuple

def get_int(prompt, lo=None, hi=None):
    while True:
        try:
            val = int(input(prompt))
            if (lo is None or lo <= val) and (hi is None or val <= hi):
                return val
        except ValueError:   # input string could not be converted to int
            pass

def do_menu(options):
    print("\nWhich do you want to do?")
    for num,option in enumerate(options, 1):
        print("{num}: {label}".format(num=num, label=option.label))
    prompt = "Please enter the number of your choice (1-{max}): ".format(max=len(options))
    choice = get_int(prompt, 1, len(options)) - 1
    options[choice].fn()    # call the requested function

def kick_goat():
    print("\nBAM! The goat didn't like that.")

def kiss_duck():
    print("\nOOH! The duck liked that a lot!")

def call_moose():
    print("\nYour trombone sounds rusty.")

Option = namedtuple("Option", ["label", "fn"])
options = [
    Option("Kick a goat", kick_goat),
    Option("Kiss a duck", kiss_duck),
    Option("Call a moose", call_moose)
]

def main():
    num = get_int("Please enter the number of iterations: ")
    for i in range(num):
        do_menu(options)

if __name__=="__main__":
    main()