Logical operators in python
In
Python, logical operators are used to perform logical operations on Boolean
values (True or False) or expressions that evaluate to Boolean values. Python
provides three logical operators: and, or, and not.
- ‘and’: The and operator returns ‘True ‘ if both
operands are ‘True’. Otherwise, it returns ‘False’.
It evaluates the second operand only if the first operand is ‘True’.
Here's an example:In this case, bothx = 5y = 10z = 3result = (x < y) and (z < y)print(result) # Output: True(x < y)and(z < y)evaluate toTrue, so the overall result of theandoperation isTrue. - `or`: The `or` operator returns `True` if at
least one of the operands is `True`. It returns `False` only if both operands
are `False`. It evaluates the second operand only if the first operand is
`False`.
Here's an example:x = 5y = 10z = 3result = (x > y) or (z < y)print(result) # Output: True
In this case, `(x > y)` evaluates to `False`, but `(z < y)` evaluates to `True`, so the overall result of the `or` operation is `True`. - `not`: The `not`
operator is a unary operator that negates the Boolean value of its operand. If
the operand is `True`, `not` returns `False`, and if the operand is `False`,
`not` returns `True`.
Here's an example:x = 5y = 10z = 3result = (x > y) or (z < y)print(result) # Output: True
In this case, `(x < y)` evaluates to `True`, but the `not` operator negates it to `False`
Logical operators are commonly used in conditional statements, loops, and boolean expressions to control the flow of the program based on certain conditions.