Booleans the yes-or-no of the programming world. In Python, we write them as True
and False
(note the capitalization).
Let's start with some basic examples to see Booleans in action.
is_teenager = True likes_pizza = False print(is_teenager) # This will print: True print(likes_pizza) # This will print: False
In these examples, is_teenager
is a Boolean variable that is set to True
, and likes_pizza
is set to False
. Pretty straightforward, right?
Booleans become super useful when we use them with comparison operators. These operators allow us to compare values and evaluate them to either True
or False
.
Here are the common comparison operators:
==
(equal to)!=
(not equal to)<
(less than)>
(greater than)<=
(less than or equal to)>=
(greater than or equal to)age = 15 print(age == 15) # True, because age is indeed 15 print(age > 20) # False, because age is not greater than 20 print(age != 10) # True, because age is not equal to 10
To make even more powerful checks, Python provides logical operators: and
, or
, and not
. These operators allow you to combine multiple conditions.
age = 15 has_permission = True # Check if someone is a teenager and has permission is_allowed = age >= 13 and age <= 19 and has_permission print(is_allowed) # True # Check if someone is either a teenager or has permission might_be_allowed = age >= 13 or has_permission print(might_be_allowed) # True # Using not to invert a Boolean value print(not has_permission) # False, because has_permission is True
One of the most common uses of Booleans is in conditional statements, where you can execute code based on whether a condition is True
or False
.
age = 15 if age >= 13 and age <= 19: print("You're a teenager!") else: print("You're not a teenager.")