python逻辑运算符''或''的技巧?

问题描述 投票:0回答:1

我正在学习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')
python operators
1个回答
1
投票

当你在条件中直接使用一个数字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')

如果你想表达一个条件来测试,要么是 ab 大于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)

5
投票
a or b > 35

相当于

a or (b > 35)

a 是真性的,因为除了 0 是真实的。你可以验证。

>>> a or b > 35
35
>>> (a or b) > 35  
False

你看 验真操作者优先.

还注意到 (a or b) > 35 成为 True 如果有 ab 大于 35.

(a or b or c or ... or n) > 35

只有当 首个非零数 歧义中大于 35


2
投票

"if a "对于一个int来说,如果a !=0,则总是会评价为true。


0
投票

其实你必须把它拆分开来才能更好地理解它.让我们来看看第一种情况。

a=35
b=35
if a or b>35:
  print('First')

在这种情况下,你的if条件由两部分组成: ab>25or 操作员意味着你至少需要其中一个是 True 打印 First.

那么,什么是 if a 其实这意味着如果a等于一个不同于 None, 0, ""False. 所以在你的情况下,a等于35,因此第一部分的评价是 True. 第二部分的评价是: False 因为b不大于35。这就是为什么它打印的是 First.

对于第四个例子,你需要它们都被评估为True才能让print语句被执行。

希望这能帮助你更好地理解它。

© www.soinside.com 2019 - 2024. All rights reserved.