Booleans represent one of two values:
TrueFalse
Boolean values are often used to make decisions and control the flow of a program.
Boolean Values
Example:
print(True)
print(False)
Output:
True
False
Boolean Variables
You can store boolean values in variables.
Example:
is_logged_in = True
is_admin = False
print(is_logged_in)
print(is_admin)
Output:
True
False
Evaluate Expressions
Many expressions return a boolean value.
Example:
print(10 > 5)
print(10 == 5)
print(10 < 5)
Output:
True
False
False
Using bool()
The bool() function evaluates a value and returns True or False.
Example:
print(bool("Hello"))
print(bool(15))
Output:
True
True
Most Values are True
Almost any value is evaluated as True if it contains data.
Example:
print(bool("Python"))
print(bool(100))
print(bool(["Apple", "Banana"]))
Output:
True
True
True
Some Values are False
The following values evaluate to False:
FalseNone00.0""(empty string)[](empty list)()(empty tuple){}(empty dictionary)
Example:
print(bool(False))
print(bool(0))
print(bool(""))
print(bool([]))
Output:
False
False
False
False
Boolean in Conditions
Boolean values are commonly used with if statements.
Example:
age = 18
if age >= 18:
print("You are an adult")
Output:
You are an adult
Functions Returning Boolean Values
Functions can return boolean values.
Example:
def is_adult(age):
return age >= 18
print(is_adult(20))
print(is_adult(15))
Output:
True
False
Practical Example
Check if a user can access a page:
is_logged_in = True
if is_logged_in:
print("Access Granted")
else:
print("Access Denied")
Output:
Access Granted
Boolean Operators
Python provides logical operators for working with boolean values.
| Operator | Description |
|---|---|
and | Returns True if both conditions are true |
or | Returns True if at least one condition is true |
not | Reverses the result |
Example:
x = 10
print(x > 5 and x < 20)
print(x > 20 or x < 20)
print(not(x > 20))
Output:
True
True
True
Summary
- Booleans have only two values:
TrueandFalse. - Comparison operations return boolean values.
- The
bool()function converts values to booleans. - Empty values such as
0,"", and[]evaluate toFalse. - Boolean values are commonly used in conditions and loops.
- Logical operators include
and,or, andnot.