How to Use Booleans in If Statements in Python
Booleans (True
and False
) are essential for controlling program flow.
This guide explores how to effectively use booleans in if
statements in Python, covering checks for explicit boolean values, truthiness, falsiness, and combining conditions with logical operators.
Checking for Boolean Values with is
The is
operator is used to check if a variable has a specific boolean value (True
or False
).
Checking for True
To check if a variable is True
, use the is
operator:
variable = True
if variable is True:
print('The boolean is True') # Output: The boolean is True
- The
is
operator compares object identities and is the recommended way to check forTrue
,False
andNone
.
Checking for False
To check if a variable is False
, use is False
or use the not
operator:
variable = False
if variable is False:
print('The boolean is False') # Output: The boolean is False
if not variable:
print('The variable stores a falsy value') # Output: The variable stores a falsy value
Always use the is
operator when comparing with boolean constants True
and False
, and when checking if a variable is None
. Do not use equality comparisons like variable == True
, which are less specific.
Checking for Truthy and Falsy Values
You can also use a boolean in an if
statement to implicitly check for its truthiness or falsiness:
variable = True
if variable:
print('The variable stores a truthy value') # Output: The variable stores a truthy value
- Python defines certain values as "truthy" and others as "falsy."
- If a variable is truthy, the
if
block runs.
The following values are considered falsy:
None
andFalse
- Numerical zero (0, 0.0, 0j, etc.).
- Empty sequences and collections:
''
,()
,[]
,{}
,set()
,range(0)
.
All other values are considered truthy:
if 'hello':
print('this runs ✅') # Output: this runs ✅
if ['a', 'b']:
print('This runs ✅') # Output: This runs ✅
if '':
print('this does NOT run ⛔️') # This does NOT run
if 0:
print('this does NOT run ⛔️') # This does NOT run
- The
if ''
statement does not run, as an empty string is considered falsy. - The
if 0
statement does not run, as numerical zero is considered falsy.
To check for a falsy value you can use the not
operator:
variable = False
if not variable:
print('The variable stores a falsy value') # Output: The variable stores a falsy value
Combining Conditions with and
and or
You can combine boolean expressions using the and
and or
operators.
-
and
: Both conditions must be true for theif
block to run.if True and True:
print('This runs ✅') # Output: This runs ✅
if True and False:
print('This does NOT run ⛔️') # This does NOT run -
or
: At least one condition must be true for theif
block to run.if True or False:
print('This runs ✅') # Output: This runs ✅
if False or False:
print('This does NOT run ⛔️') # This does NOT run