Python Booleans
In Python, booleans are a data type that represent truth values. There are two boolean values: True
and False
. Booleans are often used in programming to make decisions and control the flow of a program.
Boolean values can be assigned to variables or used directly in expressions. Here are some examples:
python
x = True
y = False
print(x) # Output: True
print(y) # Output: False
# Boolean expressions
print(5 > 3) # Output: True
print(10 == 10) # Output: True
print(7 < 2) # Output: False
# Boolean operators
print(True and False) # Output: False
print(True or False) # Output: True
print(not True) # Output: False
In addition to True
and False
, Python has a concept of “truthy” and “falsy” values. In boolean contexts (e.g., if
statements or while
loops), certain values are treated as equivalent to True
or False
. Here are some examples of truthy and falsy values:
Truthy values:
- Non-zero numbers (e.g., 1, 3.14)
- Non-empty strings (e.g., “hello”)
- Non-empty lists, tuples, sets, or dictionaries
- Functions and classes
Falsy values:
- Zero (0)
- Empty strings (e.g., “”)
- Empty lists, tuples, sets, or dictionaries
None
You can use truthy and falsy values in conditional statements. For example:
python
x = 10
if x:
print("x is truthy")
else:
print("x is falsy")
# Output: x is truthy
In this example, since x
has a non-zero value, it is considered truthy, so the code inside the if
statement executes.