Python如果语句不起作用
问题说明
我有一段无效的代码。
if difficulty=="Easy" or "easy" or "1":
with open("EasyQs.csv") as f:
allData = [line.strip().split(",") for line in f]
questions = [data[0] for data in allData]
answers = [data[1] for data in allData]
print(questions)
if difficulty=="Hard" or "hard" or "2":
with open("MediumQs.csv") as f:
allData = [line.strip().split(",") for line in f]
questions = [data[0] for data in allData]
answers = [data[1] for data in allData]
print(questions)
我尝试输入2,hard或Hard,但是它总是从 easy CSV中打印问题?
为什么?以及如何解决?
I try to type 2, hard or Hard but it always prints the questions from the 'easy' CSV? Why is this? and how can it be solved?
正确答案
在Python中,如果您要检查某项是否是一组值之一,您可以使用以下方法:
In Python, if you want to check if something is one of a set of values, you use this:
if difficulty in ("Easy", "easy", "1"):
原因是您当前正在执行的操作不起作用就像您认为的那样。您具有的条件:
The reason is that what you're doing right now doesn't work like you think it does. The conditional you have:
if difficulty == "Easy" or "easy" or "1":
实际评估如下:
if (difficulty == "Easy") or ("easy") or "1":
因为或
是比 ==
宽松的绑定运算符。因此,此总体合并条件将始终为true,因为 easy
是真实值,因此即使(difficulty == Easy)
为假,或
运算符会将其右侧评估为true并将其返回。
Because or
is a looser binding operator than ==
. So this overall combined condition will always be true, because "easy"
is a true value, so even if (difficulty == "Easy")
is false, the or
operator will evaluate its right hand side to true and return it.
这就是为什么现在您的简单案例总是会触发。
That's why right now your "easy" case always triggers.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfhckf
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20