Booleans. What is a Boolean? A Boolean is a variable which can take two values—it’s either
False. In Python,
False is equivalent to
True is equivalent to any non-zero number. Understanding the
False concept, particularly this truthiness, is key to writing Pythonic code which is more readable than it would be otherwise.
You’re going to see some examples of this later on in this section. As you’ll see, defining a Boolean is as simple as setting it to
a has been set to
True, and you can see that the type is
In addition to this, though, objects are often evaluated as being
False depending on their value. Here, setting the variable
1 means we can then evaluate it as a
bool using the
d is going to be set to the value of
5 and let’s see what happens when we track for equivalence. We’re going to see if
d is actually equal to
5 using the double equals (
==) for equivalence, rather than assignment with a single one (
This is the foundation of the way that Python understands equations. Next, you’re going to see a program which illustrates this a little more clearly. With the variable
b being set to
0, it’s then going to be checked as to whether it’s
True, using the term
if b:—this is shorthand for
if b == True:—then
'B is true!'.
This would also apply for an empty dictionary, as we’ll see here with the curly brackets. But it’s important to remember this isn’t about the values contained in there, so if we have a list with a value of
0 in it, that is not
False, as it exists.
03:32 Truthiness is a key component to writing Pythonic code, and once you understand it, your code will be clearer and simpler to understand when you come back to it, which is a key part of writing good code.
Become a Member to join the conversation.