python - 在 Python 中使用列表:使用列表函数接受输入
问题描述
我正在学习初学者 python,最近偶然发现了这个关于列表的练习问题:
你是一家奶酪店“死金刚鹦鹉”的老板,顾客来了。编写一个程序来迎接他们。您应该首先询问客户是否对切达干酪感兴趣,如果是,那么他们会获得切达干酪。否则,你说你会找到一些东西。如果他们说他们不想要奶酪,你问他们为什么在奶酪店里?在本练习中,有效的用户响应是“是”“是”“否”和“否”。任何其他回应都是“我不知道你在说什么”。您不得在此作业中使用“和”。您必须使用列表。
显然,如果允许您接受直接输入,这个问题会相对简单,但由于问题的性质与列表有关,我完全不知道如何在问题中合并列表。除了列出包含四个响应的列表并从列表中提取响应之外,我不知道从哪里开始。
这是我到目前为止所拥有的:
if __name__ == "__main__":
response = ["yes","Yes","no","No"]
like_cheese = str(input("Do you like cheese? "))
if like_cheese == response[0] or like_cheese == response[1]:
cheddar = str(input("Is cheddar ok? "))
if cheddar == response[0] or cheddar == response[1]:
print("Very well, here you are.")
elif cheddar == response[2] or response[3]:
print("Oh, then I suppose we will locate another reasonably cheesy comestible.")
else:
print("I don't know what you're talking about.")
elif like_cheese == response[2] or like_cheese == repsonse[3]:
print("Well, I don't know what you're doing in a cheese shop then.")
非常感谢任何帮助或指示,谢谢。编辑:实际上我认为这段代码可能会起作用,如果有任何方法可以优化它,或者如果有任何我忽略的东西,我很乐意接受任何建议。
解决方案
if __name__ == '__main__':
# divide list, yes/no
response_yes = ["yes", "Yes"]
response_no = ["no", "No"]
like_cheese = str(input("Do you like cheese? "))
if like_cheese in response_yes:
cheddar = str(input("Is cheddar ok? "))
if cheddar in response_yes:
print("Very well, here you are.")
elif cheddar in response_no:
print("Oh, then I suppose we will locate another reasonably cheesy comestible.")
else:
print("I don't know what you're talking about.")
elif like_cheese in response_no:
print("Well, I don't know what you're doing in a cheese shop then.")
else:
# Add: When the first input was unexpected
print("I don't know what you're talking about.")
推荐阅读
- mysql - MySQL中的数据透视表
- r - 如何在 dlm 包中建立单变量随机游走模型?
- visual-studio-code - VS Code 装饰 API - 隐藏原文
- google-cloud-platform - 无需停机即可配置谷歌云负载均衡器和托管 SSL
- javascript - 当我在惯性.js 中使用它时,vue-toastr 不起作用
- python - 在 matploltib 中何时使用 FancyArrow 以及何时使用 FancyArrowPatch?两者之间的主要区别是什么?
- powershell - 如何在任务计划程序中托管的 PowerShell 脚本中自动登录 Office-365
- java - Jetty 使用 AbstractHandler 进行异步处理
- docker - docker中的控制台应用程序不起作用
- flutter - 如何删除或更改flutter_bootstrap列之间的空间