Topic focus: booleans
What booleans are
A boolean is a "true" or "false" value.
In Python, these are written as True
and False
respectively.
How booleans are used
Booleans are usually used in if
or while
statements
to indicate whether to conditionally execute some code (if
statements)
or to continue executing code in a loop (while
statements).
Relational operators
Although booleans are true Python values, they are rarely found explicitly in Python code. Most of the time, booleans are used as the return value of a relational operator. Relational operators include:
- the
==
operator (testing equality of two values) - the
!=
operator (testing inequality of two values) - the
<
and>
operators (testing if one number is less than or greater than another) - the
<=
and>=
operators (less than or equal, greater than or equal)
as well as some less common ones.
Note that you cannot use =
to test for equality of two values,
since =
is the assignment operator.
(This is a very common pitfall of new Python programmers.)
Boolean expressions
Any Python expression that returns a boolean value is a "boolean expression".
Most often, boolean expressions are found as the test part
of an if
statement or a while
loop.
For instance, in this code:
The test part of the if
statement is x > 0
.
This is a boolean expression, because its value is True
or False
.
If you type a boolean expression into the Python interpreter, you'll see the boolean value:
Other uses of booleans
Besides being used in if
and while
statements,
sometimes we create variables with boolean values
and run some code which can take those values.
For instance, we might want to know if a value is in a list.
We could use a boolean variable for this.
list = ...
found = False
for num in list:
if num == 3:
found = True
# Now `found` will be `True` if `3` is in the list, or `False` otherwise.
Boolean values that are used this way are sometimes called flags
,
since they "flag" whether a condition is true or not.
The flag value itself will normally be used later in an if
statement:
Boolean operators: and
, or
and not
Boolean expressions can be combined
using the boolean operators and
and or
or negated using the boolean operator not
.
not
is the simplest one; it just turns True
into False
and vice-versa:
not
is really just a function,
except that you don't have to put its argument in parentheses.
(That's why we call it an "operator", not a function.)
and
and or
combine two boolean expressions into one:
The and
operator returns True
if both
the boolean expressions on its left and right are True
.
The or
operator returns True
if either
boolean expression is True
.
Both and
and or
are very low precedence,
so you don't normally have to use parentheses around
the boolean expressions they join:
As will all boolean expressions,
we usually see and
, or
, and not
in the test cases of if
statements or while
loops:
Short-circuiting behavior of and
and or
Both the and
and or
operators have a useful feature:
if you can figure out what the result will be
by just evaluating the left boolean expression,
you don't have to compute the right expression.
This is called "short-circuiting".
Here's an example where it's useful:
If the variable list
was the empty list,
then list[0]
is an error since there is no value
at index 0
in the list.
However, once the or
operator evaluates list == []
to True
,
it knows that the result of the entire or
expression must be True
(since its left argument is True
),
so it doesn't bother to evaluate its right argument.
The rules are:
- In an
or
expression, if the left argument isTrue
, the entire argument isTrue
. - In an
and
expression, if the left argument isFalse
, the entire argument isFalse
.
In the above example, if we didn't have short-circuiting, we would have had to write the example this way:
You can see that short-circuiting can make code more concise.
"Truthiness" and "falsiness"
Python isn't that picky about
what it considers to be a "true" or "false" value.
(This is in sharp constrast to Java, for instance.)
Anywhere Python is expecting a boolean expression
(e.g. in an if
statement or a while
loop),
you can use other values as well,
and they will be interpreted as either True
or False
.
The basic rule is that when a boolean value is expected,
all Python values are considered to be True
except for the following:
- the
False
value - the
None
value - the number
0
- the empty string value
""
- the empty list value
[]
- the empty dictionary value
{}
- the empty set value
set()
(and some other obscure values that you probably won't encounter.)
Note
Don't worry if you don't know what all of these are yet! We'll encounter all of these as we go along.
We say that all these values are "falsy"; everything else is "truthy". The reason Python allows this is that it allows us to write code in a more concise way. For instance, instead of writing this:
we can write this:
which is a bit more concise.
Pitfalls
There are a few pitfalls relating to booleans and boolean expression
Using =
instead of ==
The most common pitfall is to use the =
operator to test for equality.
This won't work; you need to use ==
instead.
Fortunately, Python won't allow you to do this;
if you do, you will get an error.
Using literal booleans unnecessarily
Sometimes you want to compute a boolean value from a boolean expression. It's surprising how many people will write this:
instead of the much simpler:
Always write this the shorter way.
Returning a boolean
This is a variant of the previous pitfall.
This code inside a function is technically correct:
but it's ugly. The right way to do this is like this:
If a function returns a boolean value,
you don't have to return a literal True
or False
value;
returning a boolean expression which evaluates to True
or False
is also fine (and usually a lot shorter).