Booleans
Python has a type of variable called bool
. It has two possible values: True
and False
.
布尔值
Python 有一种称为bool
的变量类型。 它有两个可能的值:True
和False
。
x = True
print(x)
print(type(x))
True
Rather than putting True
or False
directly in our code, we usually get boolean values from boolean operators. These are operators that answer yes/no questions. We'll go through some of these operators below.
我们通常从布尔运算符获取布尔值,而不是直接将True
或False
放入代码中。 这些是回答是/否问题的运算符。 下面我们将介绍其中一些运算符。
Comparison Operations
Operation | Description | Operation | Description | |
---|---|---|---|---|
|
||||
|
||||
|
比较操作符
运算符 | 描述 | 运算符 | 描述 | |
---|---|---|---|---|
|
||||
|
||||
|
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
Comparisons frequently work like you'd hope
比较经常如您所愿地发挥作用
3.0 == 3
True
But sometimes they can be tricky
但有时它们可能很棘手
'3' == 3
False
Comparison operators can be combined with the arithmetic operators we've already seen to express a virtually limitless range of mathematical tests. For example, we can check if a number is odd by checking that the modulus with 2 returns 1:
比较运算符可以与我们已经见过的算术运算符结合起来,以表达几乎无限范围的数学测试。 例如,我们可以通过检查 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
Remember to use ==
instead of =
when making comparisons. If you write n == 2
you are asking about the value of n. When you write n = 2
you are changing the value of n.
进行比较时请记住使用==
而不是=
。 如果你写n == 2
,你就是在询问 n 的值。 当你写下n = 2
时,你正在改变n的值。
Combining Boolean Values
You can combine boolean values using the standard concepts of "and", "or", and "not". In fact, the words to do this are:
.and
,
or
, and
not
With these, we can make our can_run_for_president
function more accurate.
组合布尔值
您可以使用与
、或
和非
的标准概念组合布尔值。 事实上,执行此操作的词语是:and
、or
和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
Quick, can you guess the value of this expression?
快,你能猜出这个表达式的值吗?
True or True and False
True
(Click the "output" button to see the answer)
To answer this, you'd need to figure out the order of operations.
For example, and
is evaluated before or
. That's why the first expression above is True
. If we evaluated it from left to right, we would have calculated True or True
first (which is True
), and then taken the and
of that result with False
, giving a final value of False
.
You could try to memorize the order of precedence, but a safer bet is to just use liberal parentheses. Not only does this help prevent bugs, it makes your intentions clearer to anyone who reads your code.
For example, consider the following expression:
(点击输出
按钮即可查看答案)
要回答这个问题,您需要弄清楚操作顺序。
例如,and
在or
之前计算。 这就是为什么上面的第一个表达式是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
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
But not only is my Python code hard to read, it has a bug. We can address both problems by adding some parentheses:
我想说的是今天的天气我很安全......
- 如果我有雨伞的话...
- 或者如果雨不太大并且我有兜帽的话...
- 否则,我还是很好,除非下雨并且这是一个工作日
但我的 Python 代码不仅难以阅读,而且还有一个错误。 我们可以通过添加一些括号来解决这两个问题:
prepared_for_weather = have_umbrella or (rain_level < 5 and have_hood) or not (rain_level > 0 and is_workday)
You can add even more parentheses if you think it helps readability:
如果您认为有助于可读性,您可以添加更多括号:
prepared_for_weather = have_umbrella or ((rain_level < 5) and have_hood) or (not (rain_level > 0 and is_workday))
We can also split it over multiple lines to emphasize the 3-part structure described above:
我们还可以将其拆分为多行,以强调上述的三部分结构:
prepared_for_weather = (
have_umbrella
or ((rain_level < 5) and have_hood)
or (not (rain_level > 0 and is_workday))
)
Conditionals
Booleans are most useful when combined with conditional statements, using the keywords
.if
,
elif
, and
else
Conditional statements, often referred to as if-then statements, let you control what pieces of code are run based on the value of some Boolean condition.
Here's an example:
条件语句
布尔值在与条件语句结合使用时最有用,使用关键字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
The
, a contraction of "else if".if
and
else
keywords are often used in other languages; its more unique keyword is
elif
In these conditional clauses,
statements as you would like.elif
and
else
blocks are optional; additionally, you can include as many
elif
Note especially the use of colons (
, and the following line is indented with 4 spaces. All subsequent indented lines belong to the body of the function, until we encounter an unindented line, ending the function definition.:
) and whitespace to denote separate blocks of code. This is similar to what happens when we define a function - the function header ends with
:
的缩写。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
Boolean conversion
We've seen int()
, which turns things into ints, and float()
, which turns things into floats, so you might not be surprised to hear that Python has a bool()
function which turns things into bools.
布尔转换
我们已经见过将数据转换为整数的int()
和将数据转换为浮点数的float()
,因此当您听到 Python 有一个将数据转换为布尔值的bool()
函数时,您可能不会感到惊讶 。
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
We can use non-boolean objects in if
conditions and other places where a boolean would be expected. Python will implicitly treat them as their corresponding boolean value:
我们可以在if
条件和其他需要布尔值的地方使用非布尔对象。 Python 会隐式地将它们视为相应的布尔值:
if 0:
print(0)
elif "spam":
print("spam")
spam
Your Turn
You probably don't realize how much you have learned so far. Go try the hands-on coding problems, and you'll be pleasantly surprised about how much you can do.
到你了
您可能没有意识到到目前为止您已经学到了多少。 去尝试一下动手编码问题,你会惊喜地发现你能做多少事情。