美文网首页
2.29丨逻辑与运算符

2.29丨逻辑与运算符

作者: mysterry | 来源:发表于2020-03-01 09:54 被阅读0次

布尔类型 Booleans

  • True
  • False
    比较:等于运算符(==)、大于运算符(>)、小于运算符(<)、大于等于运算符(>=)、小于等于运算符(<=)、不等于运算符(!=)

if语句

if 条件表达式:
    满足条件时要执行的命令1
    满足条件时要执行的命令2
  • if else
num = 7
if num == 5:
 print("Number is 5")
else: 
 if num == 11:
   print("Number is 11")
 else:
   if num == 7:
     print("Number is 7")
   else: 
     print("Number isn't 5, 11 or 7")
  • elif语句(else if)
num = 7
if num == 5:
  print("Number is 5")
elif num == 11:
  print("Number is 11")
elif num == 7:
  print("Number is 7")
else:
  print("Number isn't 5, 11 or 7")

一系列if…elif语句可以有一个最后的else块,用来对应最后一个elif。如果前面的if或elif表达式都不是True,则运行最后的这个else。

多个布尔值的逻辑运算

  • 布尔运算符:and or not
  1. and运算符(“与”运算符)
    接受左右两个参加运算的参数,当且仅当两个参数都为True时才计算为True。否则,计算结果为False。
>>> 1 == 1 and 2 == 2
True
>>> 1 == 1 and 2 == 3
False
>>> 1 != 1 and 2 == 2
False
>>> 2 < 1 and 3 >  6
False
  1. or运算符(“或”运算符)
    有左右两个参加运算的参数。 如果其参数中的任何一个(或两个)为True,则计算结果为True。如果两个参数均为False,则计算结果为False。
>>> 1 == 1 or 2 == 2
True
>>> 1 == 1 or 2 == 3
True
>>> 1 != 1 or 2 == 2
True
>>> 2 < 1 or 3 >  6
False
  1. not运算符(“非”运算符)
    与目前为止看到的其他两个运算符不同,not运算符仅需要一个参数,而且反转它。
    not True的结果为False,not False的结果为True。
>>> not 1 == 1
False
>>> not 1 > 7
True
if not True:
  print("1")
elif not (1 + 1 == 3):
  print("2")
else:
  print("3")

运算符优先级

  • 下面的例子表示==比or的优先级更高:
>>> False == False or True
True
>>> False == (False or True)
False
>>> (False == False) or True
True
  • 运算符优先级,排在前面优先计算


    优先级

相关文章

网友评论

      本文标题:2.29丨逻辑与运算符

      本文链接:https://www.haomeiwen.com/subject/pdemhhtx.html