Logical operators are used to combine or modify boolean values (True or False) in programming. Here are the main logical operators in Python:
-
AND (
and):- Returns
Trueif both operands areTrue. - Example:
a = True b = False result = a and b # result is False
- Returns
-
OR (
or):- Returns
Trueif at least one of the operands isTrue. - Example:
a = True b = False result = a or b # result is True
- Returns
-
NOT (
not):- Negates the boolean value of the operand. If the operand is
True, it returnsFalse, and vice versa. - Example:
a = True result = not a # result is False
- Negates the boolean value of the operand. If the operand is
Usage in Conditions
Logical operators are often used in conditional statements to control the flow of a program. For example:
if a and b:
print("Both are True")
elif a or b:
print("At least one is True")
else:
print("Both are False")
Short-Circuit Evaluation
- Python uses short-circuit evaluation for
andandor. This means:- In
a and b, ifaisFalse, Python does not evaluatebbecause the result is already determined to beFalse. - In
a or b, ifaisTrue, Python does not evaluatebbecause the result is already determined to beTrue.
- In
If you want to explore more about logical operators or see practical examples, let me know!
