The logical operator helps us to form compound conditions by combining two or more relations. Python supports the following logical operators.
- Logical AND
- Logical OR
- Logical NOT
Logical expressions are evaluated from left to right in an arithmetic expression.
Logical AND operator
This operator is used when we want to test more than one condition and make a decision.
Actually, the Logical AND operator is used to evaluate two conditions or expressions with a relational operator. If expressions on both sides(left and right side) of the Logical operator are true, then the whole expression is true.
For example, consider an expression (x>y) and (y>z), then the whole expression is true only if both expressions are true.
Example 1:
x=10 y=80 z=40 if(x>y and x>z): print("First number is maximum") elif(y>z and y>x): print("Second number is maximum") else: print("Third number is maximum")
Output:
Second number is maximum
Logical OR operator
Logical OR operator is used to simultaneously evaluate two conditions or expressions with relational operators. If one or both the expression of the logical operator is true, then the whole expression is true.
For example, (x>y) or (x>z), then the whole expression is true if either x is greater than y or x is greater than z.
Example 2:
x=90 if(x%9==0 or x%10==0): print("x is divisible by either 9 or 10") else: print("x is not divisible by 9 and 10")
Output:
x is divisible by either 9 or 10
Logical NOT operator
The logical NOT operator takes a single expression and negates the value of the expression. This operator produces a zero if the expression evaluates to a non-zero value and produces a 1 if the expression produces a zero.
Example 3:
x=90 y=80 if(not(x>y)): print("Second number is maximum") else: print("First number is maximum")
Output:
First number is maximum
Leave a comment