参考来源:Vitu.AI

今天我们来看一下 布尔值(Boolean) 的用法。Python中的布尔类型有两个常量True和False表示。

x = True
print(x)
print(type(x))

和上方的将True赋值给x的例子不同,我们通常不直接将True和False放在代码内,而是通过一些运算比较来得到布尔值,即True和False。

比较运算 + 布尔值 = ?

运算 描述
a == b a equal to b
a < b a less than b
a > b a greater than b
a <= b a less than or equal to b
a >= b a greater than or equal to b
a != b a not equal to b
def can_run_for_president(age):
    """Can someone of the given age run for president in the US?"""
    # The US Constitution says you must "have attained to the Age of thirty-five Years"
    return age >= 35

print("Can a 19-year-old run for president?", can_run_for_president(19))
print("Can a 45-year-old run for president?", can_run_for_president(45))

和python本身比起来,比较运算会更聪明一点。比如说,可以判断float和int两种类型的值。

3.0 == 3

但是也没有那么聪明。比如说,无法可以判断str和int两种类型的值。

'3' == 3

比较运算可以与我们已经看到的算术运算相组合,以表达几乎无限的数学测试范围。

例如,我们可以通过检查一个数字除以2后的余数是否返回1来判断该数字是否为奇数:

def is_odd(n):
    return (n % 2) == 1

print("Is 100 odd?", is_odd(100))
print("Is -1 odd?", is_odd(-1))

在进行比较时,请记住使用 == 而不是 = 。
如果你写n == 2,你问的是n的值。如果你写n = 2时,你正在将2赋值给n。

组合运算 + 布尔值 = ?

在Python中布尔值可以进行或、且、否三种操作,与很多语言不同的是,Python中不是用符号,而是用英文单词来表示,分别是or、and和not。

让我们再来看一个例子:

def can_run_for_president(age, is_natural_born_citizen):
    """Can someone of the given age and citizenship status run for president in the US?"""
    # The US Constitution says you must be a natural born citizen *and* at least 35 years old
    return is_natural_born_citizen and (age >= 35)

print(can_run_for_president(19, True))
print(can_run_for_president(55, False))
print(can_run_for_president(55, True))

让我们来一一解析一下。

我们设置的是一个35岁及以上的美国公民可以竞选总统。

print(can_run_for_president(19, True))是在询问一个19岁的美国公民是否可以竞选总统,答案是False。

print(can_run_for_president(55, False))是在询问一个55岁的非美国公民是否可以竞选总统,答案是False。

print(can_run_for_president(55, True))是在询问一个55岁的美国公民是否可以竞选总统,答案是True。

来猜一下下面这行代码的输出结果吧:

True or True and False

在python里,运算是有优先级的。在上述的代码中,and比or有更高的优先级。

具体来说,上述的代码中,python会先判断 True and False 这一部分,得到结果False。然后再结合前面的部分一起,判断 True or False,得到最终的结果True。

我们可以记住运算的优先级,也可以用括号来表达,这样更安全。
举个例子:

prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday

上面的代码看起来一团糟。

其实我试图说,在以下三种情况里,今天天气对我来说都是安全的:

如果我有一把伞......

如果下雨不是太重,我恰好穿了一个套头衫......

又如果虽然下雨,但是不是一个工作日(假期可以宅在家里,下不下雨对我没有影响)

但是不仅我的python代码难以阅读,而且在第三个情况里判断逻辑还有一个bug。

因而我们可以通过添加一些括号来解决这两个问题:

prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood) or not (rain_level > 0 and is_workday)

我们还可以通过换行来让三个情形看起来更一目了然:

prepared_for_weather = (
    have_umbrella 
    or ((rain_level < 5) and have_hood) 
    or (not (rain_level > 0 and is_workday))
)

 条件语句 + 布尔值 = ?

虽然布尔值本身就很有用,但是和条件语句,即配合关键词if,elif和else结合起来时,才是布尔值发挥更大作用的时候。

举个例子:

def inspect(x):
    if x == 0:
        print(x, "is zero")
    elif x > 0:
        print(x, "is positive")
    elif x < 0:
        print(x, "is negative")
    else:
        print(x, "is unlike anything I've ever seen...")

inspect(0)
inspect(-15)

和其他语言类似,python也采用if和else; 而独属于python的关键词是elif,这是“else if”的缩写,用来表达条件判断的不同情形。

在这些条件子句中,elif和else是可选的; 其中,我们可以包含任意数量的elif语句。

我们需要特别注意的是,使用冒号(:)和空格来表示单独的代码块。

这与我们定义函数时发生的情况类似。函数头以冒号(:)结尾,后面的行用4个空格缩进。 所有后续的缩进行都属于函数体,直到我们遇到一条没有缩进的行,来结束函数的定义。

def f(x):
    if x > 0:
        print("Only printed when x is positive; x =", x)
        print("Also only printed when x is positive; x =", x)
    print("Always printed, regardless of x's value; x =", x)

f(1)
f(0)

如何解释上方的代码呢?

当我们输入f(1)时,因为符合x > 0的条件,所以会分别打印三行的内容;

当我们输入f(0)时,因为不符合x > 0的条件,所以会只会打印第三行的内容;

布尔值转换


之前我们学习过int(),这个函数将值都转换为整数,而float()这个函数将值都转换为浮点数,即带有小数位的数值。

那么,可以想象,python也有一个bool()的函数,可以把事物变为布尔值。

# 所有数字都被认为是True,除了0
print(bool(1)) 
print(bool(0))
# 所有字符串都被认为是True,除了空字符串“”
print(bool("asf")) 

# 通常空的序列(字符串,列表和我们尚未看到的其他类型,如元组)是“假的”,其余的是“真实的”)
print(bool(""))

在if的条件语句中,我们也可以直接使用非布尔值,python会默默地把这些值看作相应的布尔值。

if 0:
    print(0)
elif "spam":
    print("spam")

在上面的代码中,因为0被默认是False,所以if的判断不成立,自动进入elif的判断;又因为“spam”是非空的字符串,被默认为是True,因而判断成立,所以最终的输出是“spam”。

条件的表达方式

在python里,通过条件语句里,在不同的情形下将不同的值赋予一个变量是很常见的一件事。

def quiz_message(grade):
    if grade < 50:
        outcome = 'failed'
    else:
        outcome = 'passed'
    print('You', outcome, 'the quiz with a grade of', grade)
    
quiz_message(80)

除了上述的表达方式,if的条件语句还有一行的简便的表达方式。让我们一起来看看吧。

def quiz_message(grade):
    outcome = 'failed' if grade < 50 else 'passed'
    print('You', outcome, 'the quiz with a grade of', grade)
    
quiz_message(45)

原文地址:初始python【今天开始写代码】第三课


VituTech
1 声望2 粉丝