Booleans are 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
True 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? ## Comparison Operators 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) ### Examples
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
True False True
## Logical Operators To make even more powerful checks, Python provides logical operators: `and`, `or`, and `not`. These operators allow you to combine multiple conditions. ### Examples
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
True True False
## Using Booleans in Conditional Statements One of the most common uses of Booleans is in [conditional statements](/tutorials/conditionals), where you can execute code based on whether a condition is `True` or `False`. ### Example
age = 15 if age >= 13 and age <= 19: print("You're a teenager!") else: print("You're not a teenager.")
You're a teenager!