繁体   English   中英

如何在python函数中从列表中选择项目?

[英]How do I select an item from a list in a function in python?

我正在尝试使用具有列表和集合以及ifelif语句的函数来创建菜单项。 我还试图在自己的单独模块中创建这些功能,然后将它们导入主模块。

在下面的代码中,我创建了该函数,现在我想从链接到input语句的ifelif语句开始。

当我运行代码并选择第一个选项时,CMD弹出并显示“按任意按钮继续”,而没有显示所需的输入。

我究竟做错了什么?

def Main_Menu():
    MainMenuItems = ['1. Bacon & Eggs-$2.00', '2. Full-Course Meal-$3.99', '3. Oatmeal-$1.00', '4. Hamburger & Fries-$3.00']
    print(*MainMenuItems, sep='\n')

    choice = int(input("Please select a menu item from the list above: "))

    if choice is [0]:
        print("You chose ", MainMenuItems[1])

您应该测试if choice == 0:而不是if choice is [0]:

请注意,您可以直接致电

print("You chose ", MainMenuItems[choice - 1])

打印选择的项目,不带if语句。

您不需要这样做。 而且您必须知道列表索引以0开头,因此当您选择数字1时,您将引用0索引项:

can只需打印即可完成:

print("You chose ", MainMenuItems[choice-1])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM