Boolean values in Python represent truth values, which are True
and False
. They are essential for control flow and logical operations.
Boolean Type
The Boolean type is bool
:
is_active = True
print(type(is_active)) # Output: <class 'bool'>
Logical Operators
- and: Returns
True
if both operands are true. - or: Returns
True
if at least one operand is true. - not: Inverts the truth value.
Example
a = True
b = False
print(a and b) # Output: False
print(a or b) # Output: True
print(not a) # Output: False
Boolean Conversion
Use the bool()
function to convert values to Boolean:
print(bool(0)) # Output: False
print(bool(1)) # Output: True
print(bool('')) # Output: False
print(bool('text')) # Output: True
Conclusion
Booleans are fundamental in Python programming for decision-making and controlling the flow of the program.