python - 带有 if/elif/else 语句的 While 循环
问题描述
我刚刚开始学习 Python,我在 while 循环方面遇到了一些问题。
instruction_yes_no = ""
while instruction_yes_no.lower() != "y" or "n":
instruction_yes_no = input("Do you want to see the instruction? Please write 'Y' or 'N'\n")
if instruction_yes_no.lower() == "y":
print("You are gonna lose even if you read the instructions...")
print("\n")
time.sleep(1)
instruction()
elif instruction_yes_no.lower() == "n":
print("Do you think you are better than me? I will beat you faster since you have not read the instructions")
time.sleep(1)
else:
print("You mortal...you have not chosen a valid input. Type or 'Y' or 'N'")
time.sleep(1)
break
基本上我想获得以下内容:
1)如果用户输入'y',则调用指令()函数(此工作)
2)如果用户输入'n',它会打印““你认为你比我好吗?...”(这有效)
3)如果用户没有输入'y'或'n',我想继续循环直到用户插入'y'或'n'。但是,这不起作用。
我不明白为什么。这就是我认为它应该工作的方式:
在开始时,变量指令_yes_no 设置为“”
它进入循环是因为 instruction_yes_no != than 'y' or 'n'
现在,struction_yes_no 假定用户输入的值
如果用户没有输入“y”或“n”,它应该继续循环,但不是。
解决方案
如果用户没有输入“y”或“n”,它应该保持循环,但不会
因为你有break
if-elif-else 之后。所以无论如何它都会破裂。
将中断移动到 if 块内(when instruction_yes_no.lower() == "y"
)。
推荐阅读
- c# - 独立身份服务器 4 用户名查找
- android - 更改或重置 DBFlow 中的预打包数据库
- jquery - jQuery在div中附加一个类不起作用
- php - Facebook PHP SDK 获取页面帖子数据为空
- node.js - 一个函数如何在没有条件检查调用程序/函数的情况下影响其调用者的流程
- java - JTextArea 和 Scanner JAVA 的打字机效果
- netlogo - 分发我的补丁龟,除了那些是集合的一部分
- actions-on-google - Google 模拟器上的 Actions 不接受我的“应用名称”,只有“测试应用”
- data-structures - 有没有类似数据结构的“可逆哈希表”?
- css - Oceanwp 主题的粘滞菜单