![]() |
VOOZH | about |
Logical operators are used to combine or modify conditions and return a Boolean result (True or False). They are commonly used in conditional statements to control the flow of a program based on multiple logical conditions.
Let's see an example on how logical operators AND, OR, and NOT work using Boolean variables.
Both a and c are True (AND condition). Either b or c is True (OR condition). b is False (NOT condition).
Explanation:
The following table summarizes the logical operators, their purpose, syntax and examples:
| Operator | Description | Syntax | Example |
|---|---|---|---|
| and | Returns True if both the operands are true | x and y | x>7 and x>10 |
| or | Returns True if either of the operands is true | x or y | x<7 or x>15 |
| not | Returns True if the operand is false | not x | not(x>7 and x> 10) |
A truth table shows how logical operators behave for all possible combinations of Boolean values (True and False). It helps in clearly understanding the output of AND, OR, and NOT operations.
Boolean AND operator returns True if both the operands are True else it returns False.
Example 1: Below example shows how the logical AND (and) operator works by checking if all conditions are true before executing a statement.
Numbers are greater than 0 Atleast one number is not greater than 0
Example 2: The code checks if all variables a, b and c evaluate to True, printing a message accordingly.
Atleast one number has boolean value as False
Note: If the first expression is evaluated to be false while using the AND operator, then the further expressions are not evaluated.
Boolean OR operator returns True if either of the operands is True.
Example 1: Below example demonstrates the logical OR (or) operator, where the condition becomes true if at least one of the given expressions evaluates to True.
Either of the number is greater than 0 No number is greater than 0
Example 2: The code checks if any of the variables a, b, or c has a boolean value as True; if so, it prints "At least one number has boolean value as True".
Atleast one number has boolean value as True
Note: If the first expression is evaluated to be True while using or operator, then the further expressions are not evaluated.
Boolean NOT operator works with a single boolean value. If the boolean value is True it returns False and vice-versa.
Example: Below code checks if a is divisible by either 3 or 5, otherwise, it prints a message indicating that it is not.
10 is divisible by either 3 or 5
When multiple logical operators are used in a single expression, Python evaluates them from left to right and applies short-circuit evaluation. This means Python stops evaluating further conditions as soon as the result is determined.
Method called for value: -1 Method called for value: 5 Atleast one of the number is positive
Explanation: