首页 > 解决方案 > 如何根据用户从我的列表中选择的内容打印不同的描述?

问题描述

当用户从下面的列表中选择时,我想要一个不同的描述来打印任何选择的食物。我尝试使用 elif 来分隔选择,但是当程序运行时,两个输入都在打印。

foods = ['chocolate','yogurt', 'pineapple']

print(foods)

print(input('Select a food: '))

if 'chocolate' in foods:
  print('dark and bitter ')

if 'yogurt' in foods:
  print('creamy and smooth')

标签: python

解决方案


input() 返回用户输入的行。例如,该语句selection = input('Select a food: ')会将答案分配给名为 的变量selection

然后可以检查该变量的值以确定用户做出的选择。

foods = ['chocolate','yogurt', 'pineapple']

print(foods)

selection = input('Select a food: ')

if selection == 'chocolate':
  print('dark and bitter')

elif selection == 'yogurt':
  print('creamy and smooth')

推荐阅读