Boolean Data Type for Determining True or False
To use conditional statements that execute code only under specific conditions, or loops that repeat code until a particular condition is met, you must determine whether a condition is true or false.
For example, consider writing a code that prints a is greater than 10
if the variable a
is greater than 10, and prints a is 10 or less
otherwise.
a = 11
if a > 10:
# Executes if a is greater than 10
print("a is greater than 10.")
else:
# Executes if a is 10 or less
print("a is 10 or less.")
Here, a > 10
is true if the variable a
is greater than 10, and false otherwise.
The data type that represents true
and false
in this way is called a Boolean
.
How to Use Booleans?
In Python, the value representing true
is True
, and the value representing false
is False
, with the first letter capitalized.
Variable names that represent Boolean values typically use prefixes like is_
, has_
, can_
to increase the clarity of the variable's meaning.
# Variable to determine active status
is_active = True
# Variable to determine login status
is_logged_in = False
# Variable to check certain permissions
has_permission = True
# Variable to check edit permissions
can_edit = False
Example Usage of Booleans
Booleans are commonly used in conditional statements
with if
and else
keywords to determine the truth or falsehood of a condition.
is_active = True
# Executes if is_active is True
if is_active:
print("The user is active.")
else:
print("The user is inactive.")
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.