python - 要求输入直到确切的字符串是输入问题
问题描述
这是我的 Python 代码:
choice = (input("Are you signed up? (y/n) "))
print(choice)
while True:
if choice != "y" or choice != "n":
choice = (input("Are you signed up? (y/n) "))
print(choice)
else:
break
我希望程序一直要求用户输入,直到他们输入“y”或“n”。问题是它从不接受输入,即使他们确实输入了“y”或“n”。
当我打印他们输入的内容(这是一个真实的单词)时,它说它是“y”或“n”,但它仍然不接受它。
我已经使用 Python 有一段时间了,今天我只是在尝试一些东西,但由于某种原因我无法弄清楚,我觉得这很简单明了,但我很愚蠢地注意到它。
有人可以向我解释一下吗?谢谢你。
解决方案
You need and
instead of or
in this case.
if choice != "y" and choice != "n":
or if you prefer you can do
if not (choice == "y" or choice == "n"):
You can also do:
if choice not in ("y", "n"): # THIS ONE IS PROBABLY THE BEST
or because these are each 1-character you can do:
if choice not in "yn":
You can also do:
if choice not in "Randy!" or choice in "Rad!":
推荐阅读
- function - Yii2,重定向在静态函数中不起作用
- ruby-on-rails - 我们如何循环用户注册表单 url 并通过编码在表单中填写数据并在 rails 中提交表单?
- excel - 为 AGGREGATE 公式查找关联单元格以确定列的顶部差异
- umbraco - 无法登录管理页面 umbraco 后台
- python - 用于可视化循环 ETA 的进度条
- bash - bash 如何处理不匹配的通配符?
- azure-devops - 在 Azure DevOps 中显示上周的项目
- node.js - 错误:在 window10 上找不到模块“../lib/utils/unsupported.js”
- python - 如何使用熊猫格式化excel单元格?
- python - /password-reset/ 处的 ConnectionRefusedError [WinError 10061] 无法建立连接,因为目标计算机主动拒绝它