python - 验证用户输入并执行正确的输入
问题描述
我要求用户输入 1 或 2,如果他们没有输入有效的响应,我会再次提示输入。但是,当我运行此代码时,如果输入无效,它会再次提示它们,但如果它们的新输入有效,它会继续再次提示它们,而不是执行正确输入的代码。
userInputB = int(input("Enter '1' if you would like to get out of bed, or '2' if you would like to sleep in: "))
while True:
if userInputB == 1:
print("Great! Let's move on.")
break
elif userInputB == 2:
print("Okay. You have decided to sleep in for five more minutes.")
for i in range(5,0,-1):
print(i,'...')
break
while userInputB != 1 or userInputB != 2:
print("Invalid Response.")
userInputB = int(input("Enter '1' if you would like to get out of bed, or '2' if you would like to sleep in: "))
解决方案
这一行是错误的:
while userInputB != 1 or userInputB != 2:
更改为 ( AND
):
while userInputB != 1 and userInputB != 2:
你的代码将是fine
.
推荐阅读
- html - 使用 Node js 处理 POST 请求数据
- javascript - 在编写将函数导出到全局对象的库时,我应该使用 package.json 中的浏览器字段吗?
- rxjs - 在切换到另一个可观察对象时缓冲和减少值
- tfs - TFS 发布 - 部署 - 如何在创建发布后安排部署?
- php - PHPStan 中未定义的变量,但已在其他地方声明
- ios - 处理包含能够折叠和展开的子视图的视图
- python - 无法安装 usaddress-scurgify
- php - 在 Woocommerce 的产品变体设置中隐藏重量和尺寸字段
- perl - 未正确检索哈希键值
- html - 使用选择选项元素创建弹出菜单