Data Handling in Python Class-XI
Important notes:
What is the difference between the statements print(5 & 6) and print(5 and 6)?
This is one of the most common tripping hazards in programming! While & and and look like they do the same thing, they actually have completely different purposes and mechanics.
Here is the short answer:
5 & 6outputs4because it performs a Bitwise AND (comparing the numbers bit-by-bit).5 and 6outputs6because it performs a Logical AND (evaluating truth values and using short-circuit logic).
1. print(5 & 6) Outputs 4
The ampersand (&) is the bitwise operator. It doesn’t look at 5 and 6 as whole numbers; it looks under the hood at their binary representation (0s and 1s) and aligns them.
It returns a 1 only if both aligned bits are 1.
Plaintext
0 1 0 1 (This is 5 in binary)
& 0 1 1 0 (This is 6 in binary)
-------
0 1 0 0 (This is 4 in binary)
Because only the second column has a 1 in both numbers, the result is 0100, which translates back to the integer 4.
2. print(5 and 6) Outputs 6
The keyword and is a logical (or boolean) operator. In Python, it doesn’t look at bits at all. Instead, it checks whether the values are “truthy” or “falsy”.
- In Python,
0is consideredFalse, and any non-zero number is consideredTrue. - Therefore, both
5and6are evaluated asTrue.
How Python’s and evaluates:
Python uses short-circuit evaluation for logical operators. For an and expression:
- It looks at the first value (
5). Since5isTrue, it must check the second value to see if the whole statement is true. - It moves to the second value (
6). - Python’s
andoperator actually returns the last value it evaluated to determine the truth. Because it had to check6to confirm the expression was true, it simply returns6.
Note: If you run
print(0 and 6), it would output0. Because0isFalse, Python’s short-circuit immediately returns0without even looking at the6.
Quick Summary
| Operator | Type | What it looks at | Rule / Behavior |
& | Bitwise | Binary bits (0s and 1s) | Returns 1 only if both bits are 1. |
and | Logical | Truth values (True / False) | Returns the first expression if it’s Falsy, otherwise returns the second expression. |