Logical Operators
AND Operator
he AND operator is used to combine two or more conditions in a Python program. It returns True only if all the conditions are true, otherwise, it returns False.
Example
x = 5
y = 10
z = 15
if x < y and y < z:
print("Both conditions are true")
# Output: Both conditions are true
Which of the following is a logical operator in Python?
OR Operator
The OR operator is used to combine two or more conditions in a Python program. It returns True if at least one of the conditions is true. If all conditions are false, it returns False.
Example:
x = 5
y = 10
z = 15
if x < y or y > z:
print("At least one condition is true")
#Output: At least one condition is true
NOT Operator
The NOT operator is used to negate a condition in a Python program. It returns True if the condition is false, and False if the condition is true.
Example
x = 5
if not x > 10:
print("The condition is false")
Output: The condition is false
Order of Precedence
In Python, logical operators follow the order of precedence where NOT has the highest precedence, followed by AND, and then OR.
This means that NOT operations are evaluated first, followed by AND operations, and finally OR operations.
x = 5
y = 10
z = 15
# Example 1: NOT has the highest precedence
result = not (x < y) and (y < z)
# Evaluates as: (False) and (True)
# Result: False # Example 2: OR is evaluated last result = (x < y) or (y < z) and (x > z) # Evaluates as: (True) or (True and False) # Result: True
Review: Fill in the Blanks
In contrast, the is also used to combine conditions but returns True if is true. If all conditions are false, the OR operator will return False.
The negates a condition in a Python program. It returns True if the condition is , and returns False if the condition is true.
When evaluating logical operators, it is important to understand the . The NOT operator has the highest precedence, followed by , and then . This dictates the order in which operations are evaluated in expressions.
Complete! Ready to test your knowledge?
Logical Operators
- AND Operator
- OR Operator
- NOT Operator
- Order of Precedence