Kaggle课程官网链接:Booleans and Conditionals
本专栏旨在Kaggle官方课程的汉化,让大家更方便地看懂。
目录
Booleans and Conditionals
Booleans
Comparison Operations
Combining Boolean Values
Conditionals
Boolean conversion
Your Turn
使用布尔值进行分支逻辑
Python有一种叫做bool的变量。它有两个可能的值:True和False。
x = True
print(x)
print(type(x))
True
我们通常从布尔运算符中获取布尔值,而不是直接在代码中输入True或False。
这些是回答是/否问题的操作员。我们将在下面介绍其中一些运算符。
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 than or 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 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
True
但有时它们可能很棘手
'3' == 3
False
比较运算符可以与我们已经看到的算术运算符结合使用,以表达几乎无限范围的数学测试。
例如,我们可以通过检查2的模数是否返回1来检查一个数字是否为奇数:
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
在进行比较时,请记住使用==而不是=。如果你写n==2,你是在问n的值。当你写n=2时,你在改变n的值。
您可以使用“and”、“or”和“not”的标准概念组合布尔值。事实上,要做到这一点的单词是:and,or,and not。
有了这些,我们可以使can_run_for_president函数更准确。
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 and False
True
要回答这个问题,你需要弄清楚操作的顺序。
例如,在或之前进行评估。这就是为什么上面的第一个表达式是True。
如果我们从左到右计算它,我们会先计算True或True(即True),然后用False取该结果的and,得到最终值False。
你可以试着记住优先顺序,但更安全的办法是使用括号。这不仅有助于防止错误,而且让阅读你代码的人更清楚你的意图。
例如,考虑以下表达式:
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))
我们还可以将其拆分为多行,以强调上述三部分结构:
prepared_for_weather = (
have_umbrella
or ((rain_level < 5) and have_hood)
or (not (rain_level > 0 and is_workday))
)
布尔值在与条件语句结合使用时最有用,使用关键字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,是“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)
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
我们已经看到了int(),它把东西变成int,float(),把东西变成float,所以当你听说Python有一个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
我们可以在if条件和其他需要布尔值的地方使用非布尔对象。
Python将隐式地将它们视为相应的布尔值:
if 0:
print(0)
elif "spam":
print("spam")
spam
你可能没有意识到到到目前为止你学到了多少。
去尝试动手编程问题,你会对自己能做多少感到惊喜。