python - 程序正在识别我给它的每一个输入都是正确的
问题描述
我目前正在主持一个在线寻宝游戏,其中一个步骤涉及“展开”干草捆以找到线索。出于某种原因,每当我测试它时,任何数字都被视为正确。
import random
import time
bale = int(input("Say a number 1-250 to unroll a bale of hay! It will take 45 seconds before you're told if clues are inside of it, so be willing to wait.")
if int(bale) == 63 or 190 or 36 or 106 or 127 or 89 or 84 or 44 or 80 or 124 or 173 or 202 or 224 or 51 or 220:
print "Wait 45 seconds to unroll the bale."
time.sleep(15)
print "30 seconds left..."
time.sleep(5)
print "..."
time.sleep(5)
print "20 seconds left..."
time.sleep(10)
print "10 seconds..."
time.sleep(5)
print "5 seconds..."
time.sleep(1)
print "4!"
time.sleep(1)
print "3!"
time.sleep(1)
print "2!"
time.sleep(1)
print "1!"
time.sleep(1)
print "Yes! There's a clue in here! Send a screenshot of this for confirmation to move on!"
else:
print "Wait 45 seconds to unroll the bale."
time.sleep(15)
print "30 seconds left..."
time.sleep(5)
print "..."
time.sleep(5)
print "20 seconds left..."
time.sleep(10)
print "10 seconds..."
time.sleep(5)
print "5 seconds..."
time.sleep(1)
print "4!"
time.sleep(1)
print "3!"
time.sleep(1)
print "2!"
time.sleep(1)
print "1!"
time.sleep(1)
print "Sorry, no clue. Refresh the page and try again with a new number."
解决方案
当您编写or
子句时,每个参数都被评估为布尔值。所以实际上你写的内容被解释为:
是int(bale) == 63
真的吗?还是190
真的?还是36
真的?等等。
Python 正在将这些整数转换为bool
值并评估它们是否为真。请注意,bool(n)
对于所有整数 n,除 n = 0 外,它都是假的,因此这导致条件if
始终为真。
您要做的是检查是否int(bale)
等于任何整数。这可以通过将检查更改为:
if int(bale) == 63 or int(bale) == 190 or int(bale) == 36 or...
一种更易读、更快速的方法是使用一个集合:
if int(bale) in {63, 190, 36, ...}:
推荐阅读
- python-3.x - 通过 for 循环和 API 调用,使用 Crontab 将 Django-Store 存储到 DB
- jasmine - Promise 的 Angular 单元测试
- c++ - 删除链表中不存在的节点
- npm - 三个 js 无图像材料:资产大小限制中的警告
- reactjs - 如何将文本左对齐。在反应工具提示中?
- python - 用户警告:在主线程之外启动 Matplotlib GUI 可能会失败
- c++ - 为什么在应用大小写时它没有在 switch 函数中显示默认缩进?
- html - Gmail 在 css 和表格标签文本和制动 html 之间添加了间距
- terminal - Jupyter Notebook 无法访问桌面文件和文件夹
- c++ - 有没有办法解决这个模棱两可的隐式强制转换运算符重载?