Logical Operations
Logical operations are used to combine or negate boolean values, facilitating complex conditional logic in programming.
Common Logical Operators
-
AND (
and): ReturnsTrueif both operands areTrue; otherwise, returnsFalse.a = True b = False result = a and b # False print(result) # Output: False -
OR (
or): ReturnsTrueif at least one operand isTrue; returnsFalseif both areFalse.a = True b = False result = a or b # True print(result) # Output: True -
NOT (
not): Negates the boolean value of the operand. ReturnsTrueif the operand isFalse, andFalseif the operand isTrue.a = True result = not a # False print(result) # Output: False
Combining Logical Operators
Logical operators can be combined to form more complex conditions:
a = True
b = False
c = True
result = (a and b) or c # True
print(result) # Output: True
Short-Circuit Evaluation
Logical operators use short-circuit evaluation to optimize performance:
-
AND (
and): If the first operand isFalse, the second operand is not evaluated. -
OR (
or): If the first operand isTrue, the second operand is not evaluated.def expensive_operation(): print("Operation performed") return True result = False and expensive_operation() # "Operation performed" is not printed print(result) # Output: False
Conclusion
Logical operations are fundamental for building conditions and control flow in programming. They enable complex decision-making and efficient code execution through short-circuit evaluation.