In Python, the bool
type is used to represent the logical values of truth and falsehood. bool
objects are instances of the predefined constants True
and False
.
These values are fundamental to Boolean logic in programming and are used in conditional expressions and logical operations.
Boolean values are declared using the keywords True
and False
:
true_value = True
false_value = False
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: False
or
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: True
not
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: False
Comparisons and Conditions
In Python, logical expressions return boolean values. For example:
result = 10 > 5
print(result) # Output: True
Boolean values are frequently 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
and
expression, if the first operand isFalse
, the second is not evaluated. - In an
or
expression, 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 boolean 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)