In programming, we often need to decide if a specific condition is “Right (True)” or “Wrong (False).” Python provides a dedicated data type for these two states: the Boolean type (bool).
The bool type has only two values: True and False. These are Python keywords, and the first letter must be capitalized. Writing true or false (lowercase) will result in an error.
This article explains the basic usage of the bool type and how to use it in if statements.
Basic Usage of Boolean Type
Boolean values are often used to manage the state of variables.
# Check if the system is running
is_running = True
# Check if an error has occurred
has_error = False
print(f"Running: {is_running}")
print(f"Has Error: {has_error}")
# Check the type
print(f"Type of 'is_running': {type(is_running)}")
Output:
Running: True
Has Error: False
Type of 'is_running': <class 'bool'>
Using in if Statements
Boolean values are most commonly used in conditional branching with if statements. The if statement executes the code block if the condition is True, and skips it (or runs the else block) if it is False.
def check_permission(is_admin):
"""
Receives a boolean indicating if the user is an admin,
and decides access permission.
"""
if is_admin: # Runs if is_admin is True
print("Access Granted: Admin Menu")
else: # Runs if is_admin is False
print("Access Denied: Standard User")
# Execution
check_permission(True)
check_permission(False)
Output:
Access Granted: Admin Menu
Access Denied: Standard User
Comparison Operators and Boolean Values
Instead of writing True or False directly, it is common to use comparison operators (==, !=, >, <, >=, <=) to obtain a boolean value. These operators compare two values and return True or False as the result.
user_age = 25
required_age_for_entry = 20
# The comparison operator (>=) returns a boolean value
can_enter = (user_age >= required_age_for_entry)
print(f"Comparison Result (can_enter): {can_enter}")
print(f"Type of Result: {type(can_enter)}")
if can_enter:
print("Access allowed.")
Output:
Comparison Result (can_enter): True
Type of Result: <class 'bool'>
Access allowed.
Truth Value Testing in Python
In Python, if statements can evaluate not only bool types but also other data types as “True” or “False”.
Values considered False (Falsy):
False(Boolean)None(NoneType)0(Integer),0.0(Float)""(Empty string)[](Empty list),()(Empty tuple),{}(Empty dictionary),set()(Empty set)
Values considered True (Truthy):
- All values other than the above (e.g.,
True, numbers other than 0, strings like"abc", lists with at least one element).
This allows you to write concise checks for empty lists or strings.
active_users = [] # Empty list (Falsy)
error_message = "Network Error" # Non-empty string (Truthy)
# active_users is empty, so it is evaluated as False
if active_users:
print("There are active users.")
else:
print("There are no active users.")
# error_message is not empty, so it is evaluated as True
if error_message:
print(f"Error Message: {error_message}")
else:
print("No errors.")
Output:
There are no active users.
Error Message: Network Error
Logical Operators (and, or, not)
Logical operators are used to combine multiple boolean values to create complex conditions.
not: Inverts the boolean value (not TruebecomesFalse).and: ReturnsTrueonly if both values are True.or: ReturnsTrueif at least one value is True.
is_authenticated = True
is_premium_member = False
# not
if not is_premium_member:
print("(not: Not a premium member)")
# and
if is_authenticated and is_premium_member:
print("(and: Verified Premium Member)")
else:
print("(and: Premium features not available)")
# or
if is_authenticated or is_premium_member:
print("(or: Can use basic site features)")
Output:
(not: Not a premium member)
(and: Premium features not available)
(or: Can use basic site features)
Summary
- Python’s
booltype has two values:TrueandFalse. - It is essential for controlling program flow in
ifstatements. - Comparison operators (
==,>etc.) return boolean values. - Python treats
0and empty lists ([]) asFalsein truth value testing.
