Python 允许用户使用for循环从菜单中选择选项

Python 允许用户使用for循环从菜单中选择选项,python,for-loop,Python,For Loop,我正在做一个程序的一部分,它向用户提供一个包含3个选项的菜单。我想允许用户输入他们的菜单选项1-3,然后菜单再次出现,并允许用户输入另一个选项,并重复此过程总共n次,用户在菜单之前也输入 该程序只是连续打印菜单3次,而不是在n个单独的迭代中,但我不知道如何解决这个问题 n = int(input('Please enter the number of iterations:')) for i in range(0,n): print('Enter 1 for choice 1\n')

我正在做一个程序的一部分,它向用户提供一个包含3个选项的菜单。我想允许用户输入他们的菜单选项1-3,然后菜单再次出现,并允许用户输入另一个选项,并重复此过程总共n次,用户在菜单之前也输入

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

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')

将处理选择的代码放入循环中:

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')

将以下代码缩进,右边4个空格:

if (choice == 1):
    ...
    ...
else:
    print('Invalid choice')
但是,如果我可以建议更好地实现您正在尝试的功能,那么请定义一个可以处理非数字用户输入的函数,此外,将这些打印输出带到for循环之外:


只是为了好玩:我重写了这篇文章,介绍了一些更高级的思想,如程序结构、枚举的使用、一级函数等

# 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()
# 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()