03-08 python语法入门之基本运算符之逻辑运算

一、not、and、or的基本使用

1、not

  • not:把紧跟其后的那个条件的布尔值结果取反
print(not 16 > 13)  # False
print(not True)     # False
print(not False)    # True
print(not 10)       # False
print(not 0)        # True
print(not None)     # True
print(not '')       # True

2、and

  • and:逻辑与,and用来连接左右两个条件,两个条件同时为True,最终结果才为True。两个条件有一个为False,结果一定为False.

  • 注意:只要and左边的值为Flase,and右边的值将不会执行,返回结果就是False(偷懒原则),如果为True则继续判断后面的条件

  • 以下为纯and连接左右两个条件,纯and计算顺序从左到右依次计算

#       True     True
print(True and 10 > 3)

#       True     True    True  False
print(True and 10 > 3 and 10 and 0)  # 0

#       True     True    False(and偷懒,计算0就不计算了)
print(10 > 3 and 10 and 0 and 1 > 3 and 4 == 4 and 3 != 3)  # 0

3、or

  • or:逻辑或,or用来连接左右两个条件,两个条件同时为False,最终结果才为False。两个条件有一个为True,结果一定为True。

  • 注意:只要or左边的值为True,or右边的值将不会执行,返回结果就是True(偷懒原则),如果为Flase则继续判断后面的条件。

  • 以下为纯or连接左右两个条件,纯or计算顺序从左到右依次计算

#      True(or偷懒,计算到3 > 2就不计算了)
print(3 > 2 or 0)   # True
#       True(or偷懒,计算到3 > 4就不计算了)
print(3 > 4 or False or 3 != 2 or 3 > 2 or True)    # True

二、优先级not>and>or

  • 前言:由上所知,如果单独就只是一连串的and连接,或者说单独就只是一串or连接,按照从左到右的顺序依次运算即可(偷懒原则)

  • 但是如果是混用我们就得考虑运算的优先级了,如下所示:

# 第一步计算:not 4 > 3,为False
# 第二步计算:3 > 4 and Flase,为False
# 第三步计算:1 == 3 and 'x' == 'x',为Flase(偷懒原则)
# 第四步计算:这个时候只剩下or从左到右依次计算,Flase
res = 3 > 4 and not 4 > 3 or 1 == 3 and 'x' == 'x' or 3 > 3
print(res)	# False

# 由上面我们看到,混合运算这样计算起来,混乱不堪,所以接下来我们顺着上面的优先级的顺序我们依次把两个条件使用括号括起来。
# 括号的优先级最高,优先运算。
res = (3 > 4 and (not 4 > 3)) or (1 == 3 and 'x' == 'x') or 3 > 3
print(res)	# False
  • 总结:如果是混合运算,我们按照not>and>or的优先级,把它们的左右两边的条件用括号括起来,这样计算完括号中的运算,最后只剩下or连接的左右两边的条件最后我们按照纯or的顺序,依次从左往右运算即可(偷懒原则)。

三、短路运算

  • 纯and实例
print(0 and 1)      # 0的布尔值为False,and偷懒返回当前计算位置的值:0
print({} and 1)     # {}的布尔值为False,and偷懒返回当前计算位置的值:{}
print(1 and [])     # 1的布尔值为True,and不能偷懒,继续向后运算,遇见[]的布尔值为Flase,返回当前计算位置的值:[]
print(True and 1)   # True的布尔值为True,and不能偷懒,继续向后运算,遇见1的布尔值为True,后面没有条件可以继续,返回当前计算位置的值:1
  • 纯or实例
print(0 or [] or True)  # 0的布尔值为False,or不能判断最终结果,继续向右判断条件,[]的布尔值为False,也不能判断最终结果,再继续向右运算,True的布尔值就是True,可以判段最终结果返回当前位置的值:True
print(0 or 1 or True)   # 1(偷懒原则)
print(2 or [] or {})    # 2(偷懒原则)
  • and、or、not连用
#       False(and偷懒)                  False(and没偷懒)    [](and没偷懒)
#                                                          [](or没偷懒)
print((1 > 2 and 2 < 3) or (4 and not 1 != 3) or (3 and []))    # []
  • 总结:短路运算也可以叫做逻辑运算的偷懒原则,偷懒到哪个位置就把当前位置的值返回,也就是说and、or会返回当前计算位置的值**,一旦它返回当前位置的值以后,本次运算终止。

逻辑运算预科知识:https://www.cnblogs.com/yang1333/p/12340625.html#四逻辑运算符

posted @ 2020-03-06 19:51  给你加马桶唱疏通  阅读(313)  评论(0编辑  收藏  举报