⬅ Previous Next ➡

Operators & Expressions

Arithmetic Operators
  • + Addition
  • - Subtraction
  • * Multiplication
  • / Division (gives float)
  • // Floor Division
  • % Modulus (remainder)
  • ** Exponent (power)
a = 10
b = 3

print(a + b)    # 13
print(a - b)    # 7
print(a * b)    # 30
print(a / b)    # 3.333...
print(a // b)   # 3
print(a % b)    # 1
print(a ** b)   # 1000
Relational (Comparison) Operators
  • Used to compare values (result: True/False)
  • == equal to
  • != not equal
  • > greater than
  • < less than
  • >= greater than or equal
  • <= less than or equal
x = 5
y = 10

print(x < y)     # True
print(x == y)    # False
print(x != y)    # True
Logical Operators
  • and : True if both conditions are True
  • or : True if any condition is True
  • not : reverses the result
a = 8

print(a > 5 and a < 10)   # True
print(a < 5 or a == 8)    # True
print(not(a == 8))        # False
Assignment Operators
  • = assign
  • +=, -=, *=, /= update and assign
  • //=, %=, **= floor/mod/power and assign
  • Bitwise assignment: &=, |=, ^=, <<=, >>=
x = 10
x += 5
x *= 2
x -= 3

print(x)   # 27
Bitwise Operators
  • Works on bits (integers)
  • & AND
  • | OR
  • ^ XOR
  • ~ NOT
  • << Left shift
  • >> Right shift
a = 5     # 0101
b = 3     # 0011

print(a & b)    # 1
print(a | b)    # 7
print(a ^ b)    # 6
print(~a)       # -6 (two's complement)
print(a > 1)   # 2
Membership Operators
  • in : checks if value exists in sequence
  • not in : checks if value does not exist
nums = [10, 20, 30]

print(20 in nums)        # True
print(40 not in nums)    # True

text = "python"
print("py" in text)      # True
Identity Operators
  • is : True if both variables point to the same object
  • is not : True if both are different objects
  • Note: == checks value, is checks memory reference
a = [1, 2]
b = [1, 2]
c = a

print(a == b)   # True  (same values)
print(a is b)   # False (different objects)
print(a is c)   # True  (same object)
Operator Precedence (Order of Execution)
  • Precedence decides which operator runs first.
  • Use parentheses () to avoid confusion.
High to Low (common):
1) ()
2) **
3) +x, -x, ~x
4) *, /, //, %
5) +, -
6) 
7) &
8) ^
9) |
10) =, ==, !=, in, is
11) not
12) and
13) or
14) =, +=, -= ...
Associativity (Same Precedence Direction)
  • Associativity decides direction when precedence is same.
  • Most operators: Left to Right
  • Exponent **: Right to Left
# Left to Right
print(10 - 5 - 2)     # (10 - 5) - 2 = 3

# Right to Left for **
print(2 ** 3 ** 2)    # 2 ** (3 ** 2) = 512
Expression Evaluation (Practical Program)
  • Expression evaluation follows precedence and associativity rules.
  • Parentheses change the natural order.
a = 10
b = 3
c = 2

exp1 = a + b * c
exp2 = (a + b) * c
exp3 = a > b and b > c
exp4 = a & b

print("a + b * c =", exp1)
print("(a + b) * c =", exp2)
print("a > b and b > c =", exp3)
print("a & b =", exp4)
⬅ Previous Next ➡