简体   繁体   English

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

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

I'm trying to create a menu item using functions with lists and sets as well as if and elif statements. 我正在尝试使用具有列表和集合以及ifelif语句的函数来创建菜单项。 I'm also trying to create these functions in separate modules of their own and then import them into the main module. 我还试图在自己的单独模块中创建这些功能,然后将它们导入主模块。

In the code below I've created the function and now I want to start with the if and elif statements linked to an input statement. 在下面的代码中,我创建了该函数,现在我想从链接到input语句的ifelif语句开始。

When I run the code and select the first option the CMD pops up and says "press any button to continue" without showing the desired input. 当我运行代码并选择第一个选项时,CMD弹出并显示“按任意按钮继续”,而没有显示所需的输入。

What am I doing wrong? 我究竟做错了什么?

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

You should test if choice == 0: instead of if choice is [0]: . 您应该测试if choice == 0:而不是if choice is [0]:

Note that you could directly call 请注意,您可以直接致电

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

to print the chosen item, without if statement. 打印选择的项目,不带if语句。

You don´t need an if to do so. 您不需要这样做。 And you have to know that list indexes begin with 0, so when you chose number 1, your refer to the 0 index item: 而且您必须知道列表索引以0开头,因此当您选择数字1时,您将引用0索引项:

Yo can do it with just a print: can只需打印即可完成:

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

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

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