我正在学习python,对逻辑运算符'or'有问题。找不到资料,也不明白为什么在不同的写作中代码会有不同的解释(#第一和#第二的例子有什么不同)。所以,#第一例不等于#第二例,当操作符'and'在所有代码中都相等的时候。
# First
a=35
b=35
if a or b>35:
print('First')
'''with code like above python have printed 'First' even if statement false, like i understand it.
But in other examples, statement are false too, and 'print' wasn't done, like it must be.'''
# Second
c=35
d=35
if c>35 or d>35:
print('Second')
#Third
e=35
f=35
if e>35 and f>35:
print('Third')
#Fourth
g=35
h=35
if g and h>35:
print('Fourth')
当你在条件中直接使用一个数字X时,Python会隐含地将其转换为布尔值,通过应用比较 X != 0
所以,对于你们的例子。
a=35
b=35
if a or b>35: # same as if a!=0 or b>35: True or False --> True
print('First')
c=35
d=35
if c>35 or d>35: # False or False --> False
print('Second')
e=35
f=35
if e>35 and f>35: # False and False --> False
print('Third')
g=35
h=35
if g and h>35: # same as if g!=0 and h>35: True and False --> False
print('Fourth')
如果你想表达一个条件来测试,要么是 a
或 b
大于35,不能写成 a or b > 35
. 虽然在英语中您可能很清楚,但Python并不是这样读的。
Python 要求您更明确地表达,所以您必须重复使用 > 35
:
a > 35 or b > 35
.
如果你想避免重复35,这里有一个技巧你可以使用。
if max(a,b) > 35:
# either a or b is > 35 (i.e. the highest of the two is > 35)
if min(a,b) > 35:
# both a and b are > 35 (i.e. the lowest of the two is > 35)
"if a "对于一个int来说,如果a !=0,则总是会评价为true。
其实你必须把它拆分开来才能更好地理解它.让我们来看看第一种情况。
a=35
b=35
if a or b>35:
print('First')
在这种情况下,你的if条件由两部分组成: a
和 b>25
和 or
操作员意味着你至少需要其中一个是 True
打印 First
.
那么,什么是 if a
其实这意味着如果a等于一个不同于 None
, 0
, ""
和 False
. 所以在你的情况下,a等于35,因此第一部分的评价是 True
. 第二部分的评价是: False
因为b不大于35。这就是为什么它打印的是 First
.
对于第四个例子,你需要它们都被评估为True才能让print语句被执行。
希望这能帮助你更好地理解它。