Python:如果语句不起作用? [英] Python: If statement not working?
问题描述
我有一段无效的代码。
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.
这篇关于Python:如果语句不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!