Python 运算符详解:比较、逻辑与成员运算

42 阅读3分钟

一、比较运算符

比较运算符用于比较两个值之间的关系,返回布尔值(True 或 False)。

代码

"""
比较运算符
    ==  判断==两边的值是否相等
    !=  不等于
    >   大于
    <   小于
    >=  大于等于-->大于或者等于
    <=  小于等于-->小于或者等于
逻辑运算符   逻辑运算符两边都为布尔表达式
    正确:true可以用非0的数表示
    错误:false可以用0表示
    and 并且,只有两边同时为true结果为true
    or  或者,只要有一边为true结果为true
    not 取反
成员运算符,用于测试给定数据是否在序列中
    in
    not in
"""

"""
a=10
b = 15
c = 10
d = 0
print(a==b)
print(a!=b)
print(a>b)
print(a<b)
print(a>=b) #false
print(a<=b) #true
print(a<=c) #true false
print(a>b or c>b)
print(a>b and d)
print(not d)
print(not c)
"""
# x = "Python"
# y = "P"
# print(y in x)
# print(y not in x)
a=1
b=2
c=3
d=0
#运算优先级:1、not 2、and 3、or
a>b and b>c or a+b<c
#1:假 and 假 or a+b<c
#2:假 or a+b<c
#3:假 or 假
#4:结果为假
print(a>b and b>c or a+b<c)

a-b<c or b>c and not c
#1:a-b<c or b>c and 假
#2:a-b<c or 假 and 假
#3:a-b<c or 假
#4:真 or 假
#5:结果为真
print(a-b<c or b>c and not c)

not d or b>c+a or a
#1:真 or b>c+a or a
#2:真 or 假 or a
#3:真 or a
#4:真 or 真
#5:真
print(not d or b>c+a or a)

代码结果

1.png

代码分析

  1. 第一个表达式 a>b and b>c or a+b<c

    • a=1, b=2, c=3
    • 运算顺序:not > and > or
    • 计算过程:
      • a>b = False,b>c = False
      • a>b and b>c = False and False = False
      • a+b<c = 1+2<3 = 3<3 = False
      • False or False = False
  2. 第二个表达式 a-b<c or b>c and not c

    • 计算过程:
      • a-b<c = 1-2<3 = -1<3 = True
      • b>c = 2>3 = False
      • not c = not 3 = False
      • b>c and not c = False and False = False
      • True or False = True
  3. 第三个表达式 not d or b>c+a or a

    • d=0
    • 计算过程:
      • not d = not 0 = True
      • b>c+a = 2>3+1 = 2>4 = False
      • a = 1(非0,相当于True)
      • True or False or True = True

二、逻辑运算符

逻辑运算符用于组合多个布尔表达式,Python中逻辑运算符的运算规则如下:

  1. and:只有两边都为True时,结果才为True
  2. or:只要有一边为True,结果就为True
  3. not:取反操作,True变False,False变True

重要特性

  • 在Python中,非0数值被视为True,0被视为False
  • 逻辑运算符支持短路求值:
    • and:如果第一个表达式为False,则直接返回False,不再计算第二个表达式
    • or:如果第一个表达式为True,则直接返回True,不再计算第二个表达式

三、成员运算符

成员运算符用于检查某个值是否存在于序列(如字符串、列表、元组等)中:

  • in:如果在序列中找到值,返回True
  • not in:如果在序列中没有找到值,返回True

四、运算符优先级

Python中运算符的优先级从高到低为:

  1. 算术运算符(+, -, *, /等)
  2. 比较运算符(>, <, ==等)
  3. 逻辑运算符:not > and > or