You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写Python代码实现用户通过键盘按键选择列表餐品

Got it, let's tweak your code so users can select their meal using keyboard input! First, let's fix a couple of small issues in your original code, then implement the selection feature properly.

First, fix the original code's quirks

Your menu was defined as a single string inside a list, which means random.choice would only ever spit out that whole string instead of individual meals. Also, we'll update the print syntax to work with Python 3 (the current standard).

Option 1: Basic keyboard input (enter a number + press enter)

This is the simplest approach—users type a number corresponding to their meal and hit enter. No extra libraries needed:

print("Welcome to the Mali Chef restaurant!!")
# Fix menu: each meal is a separate list item
menu = ["Meal_1", "Meal_2", "Meal_3", "Meal_4"]

print("On today's menu is:", ", ".join(menu))
print("Choose which meal you'd like to take (enter 1, 2, 3, or 4): ")

# Loop until we get valid input
while True:
    try:
        # Convert user input to integer
        user_choice = int(input())
        # Check if the number is within valid range
        if 1 <= user_choice <= len(menu):
            selected_meal = menu[user_choice - 1]  # Lists are 0-indexed
            print(f"You selected: {selected_meal}")
            break
        else:
            print(f"Oops, please enter a number between 1 and {len(menu)}!")
    except ValueError:
        # Handle non-numeric input
        print("That's not a valid number! Please type 1, 2, 3, or 4.")

Option 2: Instant key press (no enter needed)

If you want users to just press a key (1-4) without hitting enter, use the getch library to capture single key presses.

First install it via pip:

pip install getch

Then use this code:

import getch

print("Welcome to the Mali Chef restaurant!!")
menu = ["Meal_1", "Meal_2", "Meal_3", "Meal_4"]

# Print menu with numbered options for clarity
print("On today's menu is:")
for index, meal in enumerate(menu, start=1):
    print(f"  {index}. {meal}")
print("Press 1, 2, 3, or 4 to select your meal: ")

# Wait for valid key press
while True:
    pressed_key = getch.getch()
    if pressed_key in ["1", "2", "3", "4"]:
        choice_index = int(pressed_key) - 1
        selected_meal = menu[choice_index]
        print(f"\nYou selected: {selected_meal}")
        break
    else:
        print(f"\nInvalid key! Press 1, 2, 3, or 4 to choose.")

Quick breakdown:

  • Option 1: Uses a loop to validate input, ensuring users enter a valid number. We adjust for Python's 0-indexed lists to pick the right meal.
  • Option 2: The getch library captures key presses instantly, so users don't need to hit enter. We check for valid keys and select the corresponding meal right away.

内容的提问来源于stack exchange,提问作者Ivan M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:11:23