我的图片 · 在线免费的图片处理工具

前言

Python中也有逻辑运行,下面简单记录一下,not、and和or的相关知识以及使用。

记录于此方便自己查阅。

正文

主要介绍not、and和or相关内容。

含义

运算符

含义

数学对应

说明

not

非

¬

一元,把真假反过来

and

与

∧

两边都为真,结果才为真

or

或

∨

两边有一个为真,结果就为真

print(not True)      # False
print(True and False) # False
print(True or False)  # True

优先级

优先级从高到低是:

not  >  and  >  or
print(True or True and False)    # True,因为先算 and
print((True or True) and False)  # False,加括号改变顺序
print(not True and False)        # False,因为 not True 先算
print(not (True and False))      # True

建议:只要表达式稍长,就主动加括号,可读性比省两个字符重要得多。

只要前面的结果已经能决定整个表达式,后面就不再执行。

def f():
    print("f 被执行了")
    return True
print(False and f())   # f 不会执行,输出 False
print(True or f())     # f 不会执行,输出 True
s = None
if s and len(s) > 0:   # s 是 None 时,and 短路,不会调用 len(None)
    print("有内容")
lst = []
print(lst and lst[0])  # None,不会下标越界
name = input("姓名:") or "匿名用户"   # 输入为空时取默认值

陷阱:当心 falsy 值被吞掉。下面这行有问题:

score = user_input() or 0    # 如果用户输入 0,会错误地变成 0 的默认值
# 正确写法:
score = user_input() if user_input() is not None else 0

返回值

Python 跟很多语言不一样的地方:

  1. and 和 or返回的是决定结果的那个值,而不是布尔值

规则:

    • a and b:若 a 为假,返回 a;否则返回 b
    • a or b:若 a 为真,返回 a;否则返回 b
print(0 and 5)        # 0
print(3 and 5)        # 5
print(0 or 5)         # 5
print("" or [])       # []
print(2 or 0/0)       # 2(后面的除零不会执行,因为短路)

判断真假的依据是「真值测试」规则:以下值被视为 False(falsy),其余都是 True:

falsy = [False, None, 0, 0.0, "", [], {}, set(), ()]
for x in falsy:
    print(x, "->", bool(x))   # 全部 False
  1. not 返回的是纯布尔值

not 返回的是纯布尔值

跟 and / or 不同,not永远返回 True 或 False:

print(not 0)     # True
print(not [])    # True
print(not "hi")  # False

常见判断技巧:

lst = []
if not lst:          # 比 if len(lst) == 0 更地道
    print("空列表")

s = ""
if not s.strip():    # 判断是否空或全是空白
    print("无有效内容")

常见用法

用法1

多条件判断

age = 25
income = 15000

if age >= 18 and age <= 65 and income > 5000:
    print("符合条件")

# 区间判断更简洁的写法:
if 18 <= age <= 65:     # Python 支持链式比较
    print("劳动年龄")
用法2

成员检测 + 逻辑运算

role = "guest"
if role in ("admin", "editor") and role != "guest":
    print("有编辑权限")
用法3

逻辑运算的布尔结果

如果明确需要 True / False,用 bool() 包一下:

result = bool(a and b)   # 强制得到 True 或 False

容易踩的坑

坑 1

位运算符 &| 不是逻辑运算符

print(True & False)   # False,这是位运算,不是逻辑运算
print([1] and [2])    # [2],列表没有 __bool__ 重载,按真值判断

在 pandas / numpy 里必须写 &| 且要加括号,但这是另一套规则,别和 and/or 混用:

# pandas 正确写法
df[(df.age > 18) & (df.score > 60)]   # 必须加括号
坑 2

==和is` 的优先级高于逻辑运算

if x == 1 and y == 2:    # 实际是 (x == 1) and (y == 2)
    pass
坑 3

把赋值写进条件

if x = 5 and y > 0:   # SyntaxError,Python 不允许
    pass
# 正确:
x = 5
if x == 5 and y > 0:
    pass

参考文章

  1. AI
  2. Python文档

暂无评论

评论审核已启用。您的评论可能需要一段时间后才能被显示。

none
暂无评论...