python - 如何根据用户从我的列表中选择的内容打印不同的描述?
问题描述
当用户从下面的列表中选择时,我想要一个不同的描述来打印任何选择的食物。我尝试使用 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')
解决方案
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')
推荐阅读
- python - 当我想删除它时元素不存在
- python - weights = 'noisy-student' ValueError: `weights` 参数应该是 `None`、`imagenet` 或要加载的权重文件的路径
- ruby - Rails 将同一个对象的 1 字段与另一个 + 在 Active Record 中添加的字符串进行比较
- apache-spark - 在 pyspark 数据框中查找结构类型列中的文本
- email - 使用谷歌脚本将图片正确附加到电子邮件
- r - 在 R 中使用 lubridate 仅提取日期和月份并保存日期格式
- python - pytest“未找到夹具'url'”而没有使用夹具
- mongodb - GitLab CI:docker 容器无法连接到 MongoDB 服务
- php - 如何通过简单地更改wordpress中url中的id来防止登录用户访问其他用户的个人资料
- api - 如何在 Strapi.js 中创建自定义用户