1. 逻辑值检测主要用在 if while 语句中,作为条件运算或是布尔运算的操作数来使用,任何对象都可以进行逻辑值的检测。逻辑值检测可以使用bool()函数。<br /> 当一个对象被调用时,如果其所属类定义了 **bool**() 方法且返回 False 或是定义了 **len**() 方法且返回零时,其值为假值0,默认情况下均被视为真值。<br />会被视为假值的内置对象包括:<br />被定义为假值的常量: None False。<br />任何数值类型的零: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)<br />空的序列和多项集: '', (), [], {}, set(), range(0)<br />这些对象值逻辑值都为False,其对应的数值都是 0 。<br />除了以上逻辑值为 False 的对象外,其他对象的逻辑值均为 True ,对应的数值为 1。<br />
# 被定义为假值的常量的返回值都是False
# 假值常量包括:None 和 False
print(bool(None))      # False
print(bool(False))     # False

# 任何数值类型的零都会返回False
# 数值类型的0包括:0, 0.0, 0j, Decimal(0), Fraction(0, 1)
print(bool(0))         # False
print(bool(0.0))       # False
print(bool(0j))        # False

import decimal

print(bool(decimal.Decimal(0))) 

import fractions   # 分数

print(bool(fractions.Fraction(0, 1)))  # 分数0/1

# 空的序列和多项集,其len()都是0,返回值为False
# 空序列包括: '', (), [], range(0)
# 多项集包括:{}, set()
print(bool(''))        # False
print(bool(()))        # False
print(bool([]))        # False
print(bool({}))        # False
print(bool(set()))     # False
print(bool(range(0)))  # False

#产生布尔值结果的运算和内置函数总是返回 0 或 False 作为假值,1 或 True 作为真值。

布尔运算 —- and, or, not

布尔运算优先级升序排列为: or 、and、not

运算 结果 注释
x or y if x is false, then y, else x 这是个短路运算符,因此只有在第一个参数为假值时才会对第二个参数求值。
x and y if x is false, then x, else y 这是个短路运算符,因此只有在第一个参数为真值时才会对第二个参数求值。
not x if x is false, then True, else False not 的优先级比非布尔运算符低,因此 not a == b 会被解读为 not (a == b)a == not b 会引发语法错误。
<br />    一般来说,逻辑检测的结果都是True 或 False(1 或 0)。一个例外的情况是,布尔运算 or 和 and 总是返回其中一个操作数。当 or 左侧为True 时,返回值是左侧的操作数,否则返回右侧的操作数。当 and 左侧为False 时,返回值是左侧操作数,否则返回右侧操作数。
print(3 + 5 or 6 * 8)   # 返回返回值为 8
print(0 or 6 * 8)       # 返回值为 48
print(3 + 5 and 0)      # 返回值为 0
print(0 and 6 * 8)      # 返回值为 0

短路的应用:

name = input()                  # 输入姓名
gender = input() or '保密'       # 直接回车,input()值为空字符串,为False,整个表达式的值为'保密'
phonenumber = input() or '未知'  # 直接回车,input()值为空字符串,为False,整个表达式的值为'未知'
print(name,gender,phonenumber)  # 李明 保密 未知

看下面一段代码:

username,password = input().split() # 输入的字符串切分后赋值给username,password
if username == 'admin'or username == 'administrator'  and password == '123456':
    print("登录成功")

if后面是一个布尔运算,我们知道and 的优先级高于or,解释器会先解释

username == 'administrator'  and password == '123456':

将其结果做为 or 的右操作数,相当于以下代码:

if username == 'admin'or (username == 'administrator'  and password == '123456'):
此时若输入的用户名为 'admin' ,即 or 左边的表达式的值为 True,则短路右边的表达式,不再对右侧的表达式进行运算,也就是会跳过密码的验证,当用户名正确时,直接输出 "登录成功"。<br />为避免这个问题,应该用括号改变运算次序,先判定输入的用户名是否为'admin' 或 'administrator' 中的一个,结果为True 时再进行密码的验证,使代码功能与预期相符:
username,password = input().split() # 输入的字符串切分后赋值给username,password
if (username == 'admin'or username == 'administrator')  and password == '123456':
    print("登录成功")