简体   繁体   中英

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. 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.

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.

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]: .

Note that you could directly call

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

to print the chosen item, without if statement.

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:

Yo can do it with just a print:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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