DEV Community

sridhar n
sridhar n

Posted on

Python Day 4 – Bitwise, Shift and Ternary Operators

Today we finished operators and got a quick look at the full list of Python datatypes.

Datatypes in Python

int, float, complex, bool, str, bytes, bytearray, range, list, tuple, set, frozenset, dict.

Side note: Python ints have no size limit. You can store something like 675765345617234516823719832618361836128736817368173618273187 without any problem.

Bitwise operators

print(4 & 5)  # 4
print(4 | 5)  # 5
print(4 ^ 5)  # 1
Enter fullscreen mode Exit fullscreen mode

XOR (^) gives True only when the two bits are different:

a b a ^ b
T T F
T F T
F T T
F F F

The ~ (tilde) mystery

print(~4)   # -5
print(~0)   # -1
print(~-1)  # 0
Enter fullscreen mode Exit fullscreen mode

Why -5? Because negative numbers are stored in 2's complement form. The leftmost bit (MSB) is the sign: 0 means positive, 1 means negative.

How to get -5 from 5:

  1. 5 in binary → 00000101
  2. Flip every bit → 11111010
  3. Add 1 → 11111011 ← that's -5

A shortcut to remember: ~n = -(n+1)

Shift operators

print(4 >> 1)  # 2
print(4 << 1)  # 8
print(4 << 2)  # 16
print(4 << 3)  # 32
Enter fullscreen mode Exit fullscreen mode

Shifting left by 1 doubles the number. Shifting right by 1 halves it.

Ternary (conditional) operator

A one-line if/else:

no1, no2 = 10, 20
result = 100 if no1 > no2 else 200
print(result)   # 200
Enter fullscreen mode Exit fullscreen mode

You can even nest them to find the biggest of three numbers. It works, but it's hard to read:

no1, no2, no3 = 1000, 200, 30
bigger = no3 if no3 > no2 and no3 > no1 else no2 if no2 > no1 else no1
print(bigger)   # 1000
Enter fullscreen mode Exit fullscreen mode

Special operators

  • is, is not → identity
  • in, not in → membership

Top comments (0)