So far, we’ve seen str (text), int (whole numbers), and float (decimals). The fourth essential type is the Boolean (bool).
A Boolean can only be one of two things: True or False. (Note the capital letters, as Python is case-sensitive!)
is_active = True
is_logged_in = False
If you ever aren’t sure what type a variable is, use the type() function:
print(type(True)) # <class 'bool'>
print(type("Hello")) # <class 'str'>
Comparison Operators
Comparison operators ask a question. The answer is always a Boolean.
==Equal to: Checks if values are the same. (Do not use single=, as that’s for assigning names!)!=Not equal to: Checks if things are different.>,<Greater/Less than.>=,<=Greater/Less than or equal to.
print(10 == 10) # True
print(10 != 5) # True
print(10 < 5) # False
Logical Operators
Use these to combine multiple questions.
and: ReturnsTrueonly if both sides are true.or: ReturnsTrueif at least one side is true.not: Flips the value.not TruebecomesFalse.
Python evaluates not first, then and, and finally or. You can use parentheses () to force a different order or just to make the code easier to read.
Python is “lazy.” In an or statement, if the first part is True, Python doesn’t even look at the second part because the result is already decided. This is called short-circuit evaluation.
If you have one check that is a simple variable and another check that takes a long time (like searching a massive database), put the simple variable first so Python can potentially skip the heavy work entirely.
Truthy and Falsy Values
In Python, every object has an inherent “truthiness.” This means you can treat non-boolean values (like strings or numbers) as if they were True or False.
Falsy values (The “Empty” things):
- The number
0(and0.0) - An empty string
"" None(The absence of a value)
Truthy values:
- Any number other than 0 (
1,-5,0.1) - Any string with content (
" ","Hi","False")
# You can check truthiness using the bool() function
print(bool(0)) # False
print(bool("Hi")) # True
Identity (is) vs. Equality (==)
==checks if the values are the same (The data inside the box).ischecks if they are the exact same object in memory (The box itself).
For True, False, and None, Python only ever creates one copy in the computer’s memory. Therefore, you should always use is when checking for them.
x = None
# This works:
if x == None:
pass
# This is the "Professional" Python way:
if x is None:
pass
For numbers and strings, always use ==. Using is with numbers can lead to weird, unpredictable bugs because of how Python handles memory behind the scenes.