Python &&: What is Logical And Operator in Python
Python has two types of related and confusing operators.
- Logical Operator
- Bitwise Operator
If you want to use Logical and operator, then use and, for logical or operator, use or, and logical not operator, use not. The & and | is bitwise operators in Python. So don’t confuse in these operators.
Python &&
There is no && operator in Python. To use the logical and operator, use the keyword and instead of &&. If you use && operator in Python, then you will get the SyntaxError. Likewise, || and ! are not valid Python operators. Instead, use or and not operator.
Logical Operators Table
Operator (other languages) | Python equivalent operator |
&& | and |
|| | or |
! | not |
Also, the logical operators have bitwise/binary operators in Python.
Logical Operator | Bitwise Operator |
and | & |
or | | |
The logical operators have the advantage that they are short-circuited. That means if the first operand already defines the result, then the second operator isn’t evaluated at all.
And in Python
The and is a Logical AND operator in Python that returns True if both the operands are true.
x = 19 y = 21 print(x and y)
Output
21
We get the 21 because the ‘and’ tests whether both expressions are logically True.
Here, the compiler checks if the statement is True or False. If the first statement is False, it does not check the second statement and returns False immediately. This is known as “lazy evaluation”.
If the first statement is True, then the second condition is checked, and according to rules of AND operation,
True is the result only if both the statements are True.
& in Python(Bitwise)
The ‘&’ is a bitwise operator in Python that acts on bits and performs bit by bit operation.
x = 19 y = 21 print(x & y)
Output
17
The ‘&’ performs bitwise AND operation on the result of both statements.
That is it for Python && operator.