文章目录
概述
本节主要学习了布尔运算和条件运算。将非布尔值的对象转换为布尔值的过程中,所有非零数字,和非空字符串,列表,元组的返回值都是True,为零数字和空字符串、数列元组返回的值都是False。
1. 布尔运算(booleans)
Python中有一种变量类型叫做bool
。 它有两个可能的值:True
and False
x = True
print(x)
print(type(x))
'''
结果:
True
<class 'bool'>
'''
我们一般不直接在我们的code中输入True
and False
。
我们通常从**布尔操作符(boolean operators)**中获得布尔运算值(boolean values)。布尔操作符可以回答Yes/No的问题。
1.1 比较运算符(Comparison Operations)
Operation | Description | Operation | Description | |
---|---|---|---|---|
a == b | a equal to b | a != b | a not 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 |
def can_run_for_president(age):
"""Can someone of the given age run for president in the US?"""
# The US Constitution says you must be at least 35 years old
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))
'''
Can a 19-year-old run for president? False
Can a 45-year-old run for president? True
'''
3.0 == 3
# output: True
'3' == 3
# output: False
比较运算符也可以与数学运算符一起使用。
# 是否是奇数
def is_odd(n):
return (n % 2) == 1
print("Is 100 odd?", is_odd(100))
print("Is -1 odd?", is_odd(-1))
'''
Is 100 odd? False
Is -1 odd? True
'''
1.2 结合布尔运算值(Combining Boolean Values)
我们可以通过’and’, ‘or’, ‘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))
'''
False
False
True
'''
运算顺序
True or True or False
# output: True
and
在or
之前求值,这也是为什么上述运算的结果是 True。**not
的优先级先于and
;而and
的优先级先于or
** 。
运算顺寻:https://docs.python.org/3/reference/expressions.html#operator-precedence
我们可以熟记上述运算顺序,但是更安全的方法是增加括号。这不仅仅减少了bug的产生,还能让代码更清晰,更能表达意图。
例如:
prepared_for_weather = have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday
我这里尝试表达:
I’m trying to say that I’m safe from today’s weather…
- if I have an umbrella…
- or if the rain isn’t too heavy and I have a hood…
- otherwise, I’m still fine unless it’s raining and it’s a workday
但是上面代码的表达不仅难以阅读,还存在一个bug,我们可以通过增加括号(parentheses)解决问题。
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))
我们还可以将代码分成几行来强调上面想表达的三部分结构:
prepared_for_weather = (
have_umbrella
or ((rain_level < 5) and have_hood)
or (not (rain_level > 0 and is_workday))
)
2. 条件语句(conditional)
使用if
, elif
,else
这些关键词,将布尔运算与条件语句结合非常有用。
条件语句被看作 if-then 语句,运用布尔条件控制部分代码运行。
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)
'''
0 is zero
-15 is negative
'''
if
和else
也被用于其他编程语言,但elif
是python独有的,它是"else if"的缩写。在条件语句中,elif
and else
的使用是有选择的;另外,我们能尽可能多的包含elif
语句。
值得注意的是:冒号:
后,缩进行(indented line)都属于这一单独的代码块,未缩进的行表示一个代码块的结束。
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)
'''
Only printed when x is positive; x = 1
Also only printed when x is positive; x = 1
Always printed, regardless of x's value; x = 1
Always printed, regardless of x's value; x = 0
'''
3. 布尔转换(Boolean conversion)
bool()
函数将输入转化为bools。
print(bool(1)) # all numbers are treated as true, except 0
print(bool(0))
print(bool("asf")) # all strings are treated as true, except the empty string ""
print(bool(""))
# Generally empty sequences (strings, lists, and other types we've yet to see like lists and tuples)
# are "falsey" and the rest are "truthy"
'''
True
False
True
False
'''
bool()
返回值:
- 除了输入0之外,其他所有数字都是True
- 除了空字符串(“ “)外,其他所有字符串都输出True
- 一般来讲,输入任何空的序列(包括strings,lists,tuples等)都输出False
我们能在条件语句(或其他地方)中使用非布尔的对象,Python能够明确的将他们视为相应的布尔值:
if 0:
print(0)
elif "spam":
print("spam")
'''
spam
'''
他所有数字都是True
- 除了空字符串(“ “)外,其他所有字符串都输出True
- 一般来讲,输入任何空的序列(包括strings,lists,tuples等)都输出False
我们能在条件语句(或其他地方)中使用非布尔的对象,Python能够明确的将他们视为相应的布尔值:
```python
if 0:
print(0)
elif "spam":
print("spam")
'''
spam
'''