In Python, the bool type is used to represent logical values of truth and falsehood. bool objects are instances of the predefined constants True and False.
Boolean values are declared using the keywords True and False:
true_value = True
false_value = FalseThese values are fundamental to Boolean logic in programming and are used in conditional expressions and logical operations.
Operations with Boolean Values
Python supports basic logical operations with Boolean values, such as and, or, and not:
and Operator
The and operator returns True if both operands are True, otherwise it returns False.
and_result = True and False
print(and_result) # Output: Falseor Operator
The or operator returns True if at least one of the operands is True, otherwise it returns False.
or_result = True or False
print(or_result) # Output: Truenot Operator
The not operator returns True if its operand is False, and False if its operand is True, inverting the Boolean value.
not_result = not True
print(not_result) # Output: FalseComparisons and Conditions
In Python, logical expressions return Boolean values. For example:
result = 10 > 5
print(result) # Output: TrueBoolean values are often used in comparisons and conditions to control the flow of the program:
number = 10
is_greater_than_five = number > 5
if is_greater_than_five:
print("The number is greater than five")
else:
print("The number is not greater than five")Short-Circuit Evaluation
Python uses short-circuit evaluation to optimize logical operations.
- In an
andexpression, if the first operand isFalse, the second is not evaluated. - In an
orexpression, if the first operand isTrue, the second is not evaluated.
# Short-circuit evaluation with `and`
result = False and function_that_is_not_evaluated()
# Short-circuit evaluation with `or`
result = True or function_that_is_not_evaluated()Type Conversion
It is possible to convert other data types to Booleans using the bool() function:
# Conversion of numbers
number = 42
boolean_value = bool(number)
print(boolean_value) # Output: True (any non-zero number is True)
# Conversion of empty strings
empty_string = ""
boolean_value = bool(empty_string)
print(boolean_value) # Output: False (an empty string is False)