python-3.x - Python 3.x 上的基本脚本中的无限循环
问题描述
我开始在 python 3.x 中编码,在我的第一个脚本中我做了一个循环,而用户输入除 'b' 或 'B' 以外的任何其他内容时,他都留在循环中,但实际上当我输入 'b' 或 'B' 我留在循环中,我不知道为什么。
对不起我的英语我是你知道的青蛙x)
此致
我尝试用 raw_input 纠正这个问题,但似乎 raw_input() 在 python 3.x 中没有定义。
ipt2 = input ('tapez b pour quitter')
while ipt2 != 'b' or ipt2 != 'B':
print(get_random_quote(quotes))
ipt2 = input ('tapez b pour quitter')
print(ipt2)
当我键入 B 时,我会留在循环中,我认为我必须退出循环,不是吗?
最后一行在这里查看 ipt2 的值是多少。
解决方案
问题是您正在检查,or
但在这种情况下您需要使用and
:
ipt2 = input ('tapez b pour quitter')
while ipt2 != 'b' and ipt2 != 'B':
print(get_random_quote(quotes))
ipt2 = input ('tapez b pour quitter')
print(ipt2)
逻辑如下:
第一个例子
ipt2 = A
使用该行while ipt2 != 'b' and ipt2 != 'B':
,我们检查以下内容:
1) ipt2 不是 'b' (ipt2 是 A 所以正确或True
)
2) ipt2 不是 'B' (ipt2 是 A 所以正确或True
)
这两个条件都是True
如此循环继续。
第二个例子
ipt2 = B
现在我们再次检查:
1) ipt2 不是 'b' (ipt2 是 B 所以正确或True
)
2) ipt2 is not 'B' (ipt2 is B 所以不正确或False
)
一个条件是True
,另一个是False
循环继续,因为我们正在检查条件 1 或 条件 2是否为真。如果ipt2
是,'B'
则 ipt2 不是'b'
,反之亦然,一个结果将始终为 True,并且循环将继续。
推荐阅读
- mysql - 如何缩短使用之间的 sql 案例查询
- php - Laravel 路由模型绑定 - Laravel 5.7
- php - 使用表单编辑和保存 xml
- javascript - JavaScript 创建阶段何时结束,执行阶段何时开始?
- dataframe - 如何在 Spark Dataframe 中执行 Tukey HSD 测试?
- node.js - 如何围绕这个循环依赖问题进行设计?
- python - 基于Spacy规则的匹配来识别python中与金钱/日期有关系的单词
- javascript - 如何将模型数据传递给 JavaScript (Rails)
- node.js - 我如何将数据保存到一个值问题中以便稍后在我的代码中使用它
- java - Proguard 方法优化