Skip to content

Latest commit

 

History

History
421 lines (327 loc) · 11.9 KB

05_Operators.md

File metadata and controls

421 lines (327 loc) · 11.9 KB

Day 5 — Python Operators


1. Arithmetic Operators

Used for mathematical calculations.

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division (float) 5 / 2 2.5
// Floor Division 5 // 2 2
% Modulus (remainder) 5 % 2 1
** Exponentiation 2 ** 3 8
a, b = 10, 3

print(a + b)    # 13
print(a - b)    # 7
print(a * b)    # 30
print(a / b)    # 3.3333333333333335
print(a // b)   # 3  (floor: rounds DOWN always)
print(a % b)    # 1  (remainder)
print(a ** b)   # 1000

# Important: Floor division rounds toward negative infinity
print(7 // 2)   # 3
print(-7 // 2)  # -4  (not -3! floors down)
print(7 // -2)  # -4  (floors down, not toward zero)

# Modulo with negative numbers
print(-7 % 3)   # 2   (result has same sign as divisor in Python)
print(7 % -3)   # -2

# Practical use of modulo
# Check even/odd
for i in range(5):
    if i % 2 == 0:
        print(f"{i} is even")
    else:
        print(f"{i} is odd")

# Check divisibility
print(100 % 4 == 0)     # True — 100 is divisible by 4

# Wrap index (circular)
items = ["a", "b", "c"]
print(items[4 % 3])     # items[1] → 'b'

# divmod() — quotient and remainder together
q, r = divmod(17, 5)
print(f"17 ÷ 5 = {q} remainder {r}")  # 17 ÷ 5 = 3 remainder 2

# String * operator (repetition)
print("Ha" * 3)         # HaHaHa
print([0] * 5)          # [0, 0, 0, 0, 0]

2. Assignment Operators

Used to assign values to variables.

Operator Equivalent Example
= x = 5 Assign
+= x = x + 5 Add and assign
-= x = x - 5 Subtract and assign
*= x = x * 5 Multiply and assign
/= x = x / 5 Divide and assign
//= x = x // 5 Floor divide and assign
%= x = x % 5 Modulo and assign
**= x = x ** 5 Exponent and assign
&= x = x & 5 Bitwise AND and assign
|= x = x | 5 Bitwise OR and assign
^= x = x ^ 5 Bitwise XOR and assign
>>= x = x >> 5 Right shift and assign
<<= x = x << 5 Left shift and assign
:= Walrus operator Assign and return
x = 10
x += 5;   print(x)   # 15
x -= 3;   print(x)   # 12
x *= 2;   print(x)   # 24
x //= 5;  print(x)   # 4
x **= 2;  print(x)   # 16
x %= 5;   print(x)   # 1

# Walrus operator := (Python 3.8+) — assign inside an expression
data = [1, 5, 3, 8, 2]
if (n := len(data)) > 4:
    print(f"List is long: {n} items")  # List is long: 5 items

# Useful in while loops
import random
while (num := random.randint(1, 10)) != 5:
    print(f"Got {num}, trying again...")
print(f"Finally got 5!")

3. Comparison Operators

Used to compare values. Always return True or False.

Operator Name Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 5 < 3 False
>= Greater than or equal 5 >= 5 True
<= Less than or equal 5 <= 3 False
print(10 == 10)     # True
print(10 == "10")   # False (different types)
print(10 != 20)     # True
print(10 > 5)       # True
print(10 < 5)       # False

# Chained comparisons (Pythonic!)
x = 5
print(1 < x < 10)      # True — chained: equivalent to (1 < x) and (x < 10)
print(1 < x < 10 < 20) # True

# Comparing strings (lexicographic)
print("apple" < "banana")   # True (a comes before b)
print("z" > "a")            # True

# Comparing lists
print([1, 2, 3] == [1, 2, 3])  # True (same content)
print([1, 2] < [1, 3])         # True (compared element by element)

# == vs is
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)   # True  (same value)
print(a is b)   # False (different objects in memory)
print(a is c)   # True  (same object — c is alias for a)
print(id(a), id(b), id(c))

4. Logical Operators

Used to combine boolean expressions.

Operator Description Example
and True if BOTH are True True and False → False
or True if ANY one is True True or False → True
not Inverts boolean value not True → False
x = 5

# and — short-circuits: stops at first False
print(x > 0 and x < 10)    # True
print(x > 0 and x > 10)    # False

# or — short-circuits: stops at first True
print(x < 0 or x < 10)     # True
print(x < 0 or x > 10)     # False

# not
print(not True)             # False
print(not False)            # True
print(not (x > 10))         # True

# Short-circuit evaluation — very important!
# 'and' stops at first False
result = False and print("This will NOT print")  # print never called

# 'or' stops at first True
result = True or print("This will NOT print")    # print never called

# Practical use of short-circuit
name = None
display = name or "Stranger"          # "Stranger" (since name is falsy)
print(display)

name = "Logesh"
display = name or "Stranger"          # "Logesh" (since name is truthy)
print(display)

# 'and' with non-boolean values
# Returns first falsy value, or last value if all truthy
print(5 and 10)        # 10 (both truthy, returns last)
print(0 and 10)        # 0  (0 is falsy, returns it)
print("hi" and "bye") # "bye" (both truthy)

# 'or' with non-boolean values
# Returns first truthy value, or last value if all falsy
print(0 or "hello")   # "hello" (0 is falsy, tries next)
print([] or {})       # {} (both falsy, returns last)
print("hi" or "bye")  # "hi" (first truthy)

# Real-world pattern: Default values
config = {}
host = config.get("host") or "localhost"
port = config.get("port") or 8080

5. Identity Operators

Tests whether variables refer to the SAME object in memory.

Operator Description
is True if both are the same object
is not True if NOT the same object
# 'is' checks identity (same memory address), not equality
a = [1, 2, 3]
b = [1, 2, 3]
c = a

print(a == b)    # True  (equal values)
print(a is b)    # False (different objects)
print(a is c)    # True  (c is same object as a)

# Python caches small integers (-5 to 256) and short strings
x = 100
y = 100
print(x is y)   # True (cached!)

x = 1000
y = 1000
print(x is y)   # False (not cached, different objects)

# Always use 'is' for None, True, False
result = None
if result is None:       # CORRECT
    print("No result")

if result == None:       # AVOID — works but not Pythonic
    print("No result")

# Never use 'is' to compare values!
# x is 5   # may work for small ints (cached) but unreliable
# x == 5   # ALWAYS use == for value comparison

6. Membership Operators

Tests whether a value exists in a sequence.

Operator Description
in True if value found in sequence
not in True if value NOT found in sequence
fruits = ["apple", "banana", "cherry"]

print("apple" in fruits)        # True
print("mango" in fruits)        # False
print("mango" not in fruits)    # True

# Works on strings, lists, tuples, sets, dicts
print("py" in "python")         # True (substring check)
print("z" not in "python")      # True

# Dictionary — checks KEYS
d = {"name": "Logesh", "age": 25}
print("name" in d)              # True
print("Logesh" in d)            # False (checks keys, not values!)
print("Logesh" in d.values())   # True (check values explicitly)

# Performance comparison
import time

large_list = list(range(1_000_000))
large_set = set(range(1_000_000))

# List membership — O(n) linear search
start = time.time()
999999 in large_list
print(f"List: {time.time() - start:.6f} seconds")

# Set membership — O(1) hash lookup
start = time.time()
999999 in large_set
print(f"Set:  {time.time() - start:.6f} seconds")   # MUCH faster!

7. Bitwise Operators

Operate on binary representations of integers.

Operator Name Example Binary Result
& AND 12 & 10 1100 & 1010 1000 = 8
| OR 12 | 10 1100 | 1010 1110 = 14
^ XOR 12 ^ 10 1100 ^ 1010 0110 = 6
~ NOT ~12 ~00001100 11110011 = -13
<< Left shift 3 << 2 11 << 2 1100 = 12
>> Right shift 12 >> 2 1100 >> 2 11 = 3
a = 12    # binary: 1100
b = 10    # binary: 1010

print(a & b)    # 8   binary: 1000 (AND: 1 only where both have 1)
print(a | b)    # 14  binary: 1110 (OR: 1 where any has 1)
print(a ^ b)    # 6   binary: 0110 (XOR: 1 where exactly one has 1)
print(~a)       # -13 (bitwise NOT: flips all bits → -(n+1))
print(a << 2)   # 48  (left shift: multiply by 2^2 = 4)
print(a >> 2)   # 3   (right shift: divide by 2^2 = 4)

# Practical use cases:
# Check if number is even (fast)
n = 42
print(n & 1)        # 0 means even, 1 means odd

# Multiply/divide by powers of 2 (fast)
print(5 << 1)       # 10  (5 * 2)
print(5 << 2)       # 20  (5 * 4)
print(20 >> 2)      # 5   (20 / 4)

# Bitwise flags (common in systems programming)
READ = 0b001    # 1
WRITE = 0b010   # 2
EXEC = 0b100    # 4

permissions = READ | WRITE    # 0b011 = 3
print(permissions & READ != 0)   # True — has read permission
print(permissions & EXEC != 0)   # False — no execute permission

# XOR trick: swap without temp variable
x = 5
y = 10
x ^= y    # x = x ^ y
y ^= x    # y = y ^ x
x ^= y    # x = x ^ y
print(x, y)  # 10 5 — swapped!

# XOR trick: check if two booleans differ
a, b = True, False
print(bool(a ^ b))  # True — they differ

Operator Precedence (Order of Operations)

From highest to lowest:

Precedence Operators
1 (highest) () parentheses
2 ** exponentiation
3 +x, -x, ~x unary
4 *, /, //, %
5 +, -
6 <<, >>
7 &
8 ^
9 |
10 ==, !=, >, <, >=, <=, is, is not, in, not in
11 not
12 and
13 (lowest) or
# Precedence examples
print(2 + 3 * 4)        # 14 (not 20) — * before +
print((2 + 3) * 4)      # 20 — parentheses first
print(2 ** 3 ** 2)      # 512 (not 64) — ** is right-associative: 2**(3**2) = 2**9
print(3 > 2 and 5 < 10) # True
print(not 5 > 3)        # False — not has lower precedence than >

# When in doubt, use parentheses!
result = (5 * 3) + (10 // 4) - (2 ** 2)
print(result)   # 15 + 2 - 4 = 13

🎯 Mentor Questions

Q: What is short-circuit evaluation?

A: Python's and and or operators don't always evaluate both operands. and stops at the first falsy value, or stops at the first truthy value. This is useful for default values (name = user_input or "Guest") and guard clauses (data and process(data)).

Q: What is the difference between == and is?

A: == compares values (are the contents equal?). is compares identity (are both variables pointing to the exact same object in memory?). Always use is when checking for None, and == for value comparisons.

Q: What does the walrus operator := do?

A: It's the assignment expression operator (Python 3.8+). It assigns a value to a variable AND returns that value in the same expression. Useful in while loops and if conditions to avoid evaluating an expression twice.


📝 Day 5 Quick Revision

Category Operators Key Point
Arithmetic +, -, *, /, //, %, ** / always float, // floors down
Assignment =, +=, -=, etc., := := is walrus (3.8+)
Comparison ==, !=, >, <, >=, <= Returns True/False
Logical and, or, not Short-circuits!
Identity is, is not Same object? Use for None
Membership in, not in Set O(1), List O(n)
Bitwise &, |, ^, ~, <<, >> Binary operations