'and' is a logical operator that returns True if both operands are logically true, whereas '&' is a bitwise operator that performs bit-by-bit AND operations on integers.
Note: In logical context, 0 is considered False and any non-zero value is considered True.
and Operator
The 'and' keyword in Python is used for logical operations. It combines two conditions and returns True only if both conditions are true; otherwise, it returns False.
n1 = 5
n2 = 10
if n1>3 and n2<10:
print("both are correct")
else:
print ("one is wrong")
Output
one is wrong
Explanation: n1 > 3 is true, but n2 < 10 is false, so the overall condition fails and the else block executes.
& Operator
The '&' symbol is a bitwise AND operator. It operates on the binary representation of integers and performs AND operation on each corresponding bit.
n1 = 14
n2= 10
print (n1 & n2)
Output
10
Explanation: 14 in binary is 1110 and 10 in binary is 1010, bitwise AND on these two will give us 1010 which is 10 in integers.
Difference between 'and' Operator and '&' Symbol
Let us compare both operators side by side.
a = 14
b = 4
print(b and a)
print(b & a)
Output
14 4
Explanation:
- and operator checks if both values are logically True and returns the last evaluated value if they are. In 4 and 14 returns 14
- & operator performs bitwise AND on the numbers. 4 (0100) & 14 (1110) -> 4