๐ Day 02 : Operators and Expressions
๐ฏ Enterprise Objective
Operators are the verbs of Python โ they act on data. Today we master every operator category, from basic arithmetic to bitwise manipulation and the modern walrus operator. You will learn not just what each operator does, but when and why to use it in professional data pipelines.
๐ Strategic Overview
| # | Category | Operators | Core Use Case | |
|---|---|---|---|---|
| 1 | Arithmetic | +, -, , /, //, %, * | Numeric computations | |
| 2 | Assignment | +=, -=, *=, /=, etc. | In-place modification | |
| 3 | Comparison | ==, !=, <, >, <=, >= | Filtering & validation | |
| 4 | Logical | and, or, not | Boolean logic | |
| 5 | Identity & Membership | is, in | Object inspection | |
| 6 | Bitwise | &, `\ | , ^, ~, <<, >>` | Binary manipulation |
| 7 | Ternary | x if cond else y | Inline conditionals | |
| 8 | Precedence | (evaluation order) | Correct formula design | |
| 9 | Short-Circuit | and/or early exit | Safe access patterns | |
| 10 | Walrus | := | Assignment expressions |
1. Arithmetic Operators : Numeric Operations
Python has 7 built-in arithmetic operators: + (add), - (subtract), (multiply), / (true division), // (floor division), % (modulo), and * (exponentiation). These are the fundamental building blocks for all numerical computations.
Quick Reference:
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | True Division | 7 / 3 | 2.333... |
// | Floor Division | 7 // 3 | 2 |
% | Modulo | 7 % 3 | 1 |
** | Power | 2 ** 10 | 1024 |
๐ผ Why Data Analysts Care
โข Financial calculations: profit = revenue - costs
โข Metrics generation: margin = (profit / revenue) * 100
โข Batch processing: Using modulo % to execute code every Nth row
โ ๏ธ Division Always Returns Float
The / operator always returns a float, even if the result is whole: 10 / 2 โ 5.0. Use // for integer results.
๐ง Pro Tip
Exponentiation evaluates right-to-left: 232 = 2(32) = 29 = 512, not (23)**2 = 64.
๐งช Concept Checks: Arithmetic
Q1. Compute 17 // 5 and 17 % 5. Verify: 5 * (17//5) + (17%5) == 17. Print all values and the verification.
Q2. Write code that computes the area of a circle with radius r = 7.5 using pi = 3.14159. Print the result rounded to 2 decimal places.
Q3. Given x = -7 and y = 2, compute x / y, x // y, and x % y. Explain why x // y is -4 and not -3.
Q4. Write code to extract the tens digit from n = 4567 using only // and % operators. Print the result.
Q5. Compute 232 and (23)2. Print both results and explain why they differ (right-to-left associativity).
2. Assignment Operators : In-Place Operations
Assignment operators combine an arithmetic or bitwise operation with assignment. Instead of writing x = x + 5, you write x += 5. Python supports: +=, -=, =, /=, //=, %=, *=, and bitwise variants.
| Operator | Equivalent | Example |
|---|---|---|
x += 5 | x = x + 5 | Accumulate totals |
x -= 3 | x = x - 3 | Decrease counters |
x *= 2 | x = x * 2 | Scale values |
x //= 4 | x = x // 4 | Integer reduction |
x **= 2 | x = x ** 2 | Square values |
๐ผ Why Data Analysts Care
โข Running totals: Accumulating sums in loops: total += row_value
โข Counter patterns: count += 1 is the most common pattern in data pipelines
โข Scaling: Normalize columns: col *= scale_factor
โ ๏ธ Immutable Types
For immutable types like str and tuple, += creates a new object rather than modifying in-place. This can be a performance trap in tight loops.
๐ง Pro Tip
Use x = -1 to flip the sign of a number. Use x *= 0.5 for square root.
๐งช Concept Checks: Assignment
Q1. Start with balance = 1000. Apply these in order: += 500, -= 200, *= 1.1, //= 1. Print balance after each step.
Q2. Write a loop that computes n! (factorial) for n = 10 using only *=. Print the result and verify with math.factorial(10).
Q3. Create text = "Hello". Use += to append " World". Then check if id(text) changed (proving a new object was created). Print both IDs.
Q4. Start with x = 256. Apply //= 2 repeatedly in a loop until x < 1. Count and print how many iterations it took.
Q5. Write code that uses %= to keep an angle within 0-359 degrees. Test with angle = 750. Print the normalized angle.
3. Comparison Operators : Relational Logic
Comparison operators evaluate two values and return a bool (True or False). Python supports: ==, !=, <, >, <=, >=. A unique Python feature is chained comparisons: 1 < x < 10.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | 5 == 5 โ True |
!= | Not equal | 5 != 3 โ True |
< | Less than | 3 < 5 โ True |
> | Greater than | 5 > 3 โ True |
<= | Less or equal | 5 <= 5 โ True |
>= | Greater or equal | 6 >= 5 โ True |
๐ผ Why Data Analysts Care
โข Data filtering: df[df['age'] >= 18] โ core of pandas filtering
โข Validation: Check thresholds: if revenue > target:
โข Sorting logic: Custom sort keys rely on < and > comparisons
โ ๏ธ == vs is
== checks value equality, is checks identity (same object in memory). Never use is to compare values; use it only for None checks: if x is None.
๐ง Pro Tip
Python supports chained comparisons: 0 <= x < 100 is equivalent to 0 <= x and x < 100 but cleaner and faster.
๐งช Concept Checks: Comparison
Q1. Given a = 10 and b = 10.0, test a == b and a is b. Print results and explain the difference between value equality and identity.
Q2. Write a chained comparison that checks if temperature = 37.5 is in the "normal" range (36.1 to 37.2). Print the result.
Q3. Compare strings: "apple" < "banana", "Apple" < "apple". Print results and explain how Python compares strings (lexicographic, Unicode order).
Q4. Write code that finds the maximum of three numbers a, b, c using only comparison operators (no max() built-in). Test with a=15, b=42, c=8.
Q5. Demonstrate that None == None is True but None == 0 is False and None == False is False. Why should you always use is None instead?
4. Logical Operators : Boolean Algebra
Python has three logical operators: and, or, and not. They combine boolean expressions. Crucially, and and or use short-circuit evaluation โ they stop evaluating as soon as the result is determined.
| Operator | Returns True if... | Short-circuits when... |
|---|---|---|
and | Both operands are truthy | Left operand is falsy |
or | At least one is truthy | Left operand is truthy |
not | Operand is falsy | Never |
๐ผ Why Data Analysts Care
โข Multi-condition filters: df[(df['age'] > 18) & (df['score'] > 90)]
โข Data validation: if name and len(name) > 0: โ safe null checking
โข Default values: result = value or 'N/A' โ using or for defaults
โ ๏ธ and/or Return Values, Not Booleans
and returns the first falsy value or the last value. or returns the first truthy value or the last value. 'hello' and 42 โ 42, not True.
๐ง Pro Tip
value or default is a common Python idiom for providing default values: name = user_input or 'Anonymous'.
๐งช Concept Checks: Logical
Q1. Given x = 5, evaluate and print: x > 3 and x < 10, x > 3 or x < 2, not(x > 3 and x < 10). Explain each result.
Q2. Demonstrate short-circuit evaluation: write code where and prevents a ZeroDivisionError. Print a message proving the second operand was never evaluated.
Q3. Write code showing that "hello" and 42 returns 42, while "" and 42 returns "". Explain why and/or return values, not booleans.
Q4. Write a function is_valid_age(age) that returns True only if age is an integer, positive, and less than 150. Use and chaining.
Q5. Use or to set defaults: given user_name = "" and fallback = "Guest", compute display_name = user_name or fallback. Print the result.
5. Identity & Membership : Object Inspection
Identity operators (
is, is not) check whether two variables point to the same object in memory. Membership operators (in, not in) check whether a value exists inside a container (list, tuple, dict, set, string).
| Operator | Purpose | Example |
|---|---|---|
is | Same object? | x is None |
is not | Different objects? | x is not None |
in | Value in container? | 'a' in 'abc' โ True |
not in | Value absent? | 5 not in [1,2,3] โ True |
๐ผ Why Data Analysts Care
โข Null checking: if value is None: โ the Pythonic way to check for null
โข Data validation: if col in df.columns: โ safe column access
โข Search & lookup: if key in my_dict: โ O(1) dict membership
โ ๏ธ Integer Caching
Python caches integers from -5 to 256. So a = 100; b = 100; a is b โ True, but a = 1000; b = 1000; a is b โ False (different objects, same value).
๐ง Pro Tip
For dict and set, in is O(1). For list, in is O(n). Choose your data structure wisely for frequent membership tests.
๐งช Concept Checks: Identity & Membership
Q1. Create a = [1, 2] and b = a and c = [1, 2]. Test a is b, a is c, a == c. Print results and explain each.
Q2. Demonstrate Python's integer caching: test a = 256; b = 256; print(a is b) then a = 257; b = 257; print(a is b). Explain the results.
Q3. Write code that checks if a column name "salary" exists in a list of column headers ["name", "age", "salary", "dept"]. Use the in operator.
Q4. Given d = {"x": 1, "y": 2}, demonstrate that in checks keys (not values): test "x" in d and 1 in d. Print results.
Q5. Write code showing None is None is True (singleton pattern). Then show why if x is None: is preferred over if x == None: (custom eq risk).
6. Bitwise Operators : Binary-Level Control
Bitwise operators work on the binary (base-2) representation of integers. Python supports: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).
| Operator | Name | Example | Result | ||
|---|---|---|---|---|---|
& | AND | 5 & 3 | 1 | ||
| `\ | ` | OR | `5 \ | 3` | 7 |
^ | XOR | 5 ^ 3 | 6 | ||
~ | NOT | ~5 | -6 | ||
<< | Left shift | 5 << 1 | 10 | ||
>> | Right shift | 5 >> 1 | 2 |
๐ผ Why Data Analysts Care
โข Flag management: Using bitmasks to store multiple boolean flags in one integer
โข Performance: Left shift << 1 is faster multiplication by 2
โข Hashing: XOR is used in hash functions and checksums
๐ง Pro Tip
n & 1 checks if n is odd (returns 1) or even (returns 0). n & (n-1) checks if n is a power of 2 (returns 0 if yes).
๐งช Concept Checks: Bitwise
Q1. Convert a = 12 and b = 10 to binary using bin(). Then compute a & b, a | b, a ^ b and verify the results match the binary math.
Q2. Write code that uses << 1 to multiply by 2 and >> 1 to divide by 2. Test with n = 42. Compare results with * 2 and // 2.
Q3. Write a function is_odd(n) using n & 1. Test with 5 numbers. Explain why this works at the binary level.
Q4. Write a function is_power_of_two(n) using n & (n - 1) == 0. Test with [1, 2, 3, 4, 8, 16, 18]. Handle edge case n <= 0.
Q5. Compute ~5 and explain why the result is -6. Relate it to two's complement: ~n = -(n+1).
7. Ternary Operator : Inline Conditionals
The ternary (conditional) operator provides a one-line if-else expression: value_if_true if condition else value_if_false. It is an expression (returns a value), not a statement.
status = 'Adult' if age >= 18 else 'Minor'
๐ผ Why Data Analysts Care
โข Column creation: df['label'] = df['val'].apply(lambda x: 'High' if x > 50 else 'Low')
โข Default handling: name = input_val if input_val else 'Unknown'
โข Compact logic: Replace 4-line if/else blocks with clean one-liners
โ ๏ธ Nested Ternaries
Nesting ternaries like 'A' if x > 90 else 'B' if x > 80 else 'C' works but reduces readability. Use sparingly.
๐งช Concept Checks: Ternary
Q1. Given x = -5, use the ternary operator to compute abs_x (absolute value) without using abs(). Print the result.
Q2. Write a ternary expression that returns "even" if n is even, "odd" otherwise. Test with n = 7 and n = 12.
Q3. Use a nested ternary to classify temp = 35 as "Cold" (< 15), "Warm" (15-30), or "Hot" (> 30). Print the result.
Q4. Write a ternary that sets discount = 0.2 if is_member else 0.05. Test with is_member = True and is_member = False.
Q5. Use a ternary inside an f-string: f"You have {n} item{'s' if n != 1 else ''}". Test with n = 1 and n = 5.
8. Operator Precedence : Order of Evaluation
When an expression has multiple operators, Python follows a strict precedence hierarchy. Higher-precedence operators are evaluated first. When precedence is equal, associativity (left-to-right or right-to-left) determines the order.
| Priority | Operators | Associativity |
|---|---|---|
| Highest | ** | Right-to-left |
~, +x, -x (unary) | Right-to-left | |
*, /, //, % | Left-to-right | |
+, - | Left-to-right | |
<<, >> | Left-to-right | |
<, <=, >, >=, ==, != | Left-to-right | |
not | Right-to-left | |
and | Left-to-right | |
| Lowest | or | Left-to-right |
๐ผ Why Data Analysts Care
โข Debugging: Understanding precedence prevents subtle calculation bugs
โข Code clarity: Explicit parentheses make complex formulas readable
โข Formula translation: Converting math formulas to code requires correct operator order
๐ง Pro Tip
When in doubt, use parentheses. They cost nothing at runtime and prevent bugs: (a + b) * c is clearer than relying on precedence.
๐งช Concept Checks: Precedence
Q1. Evaluate 2 + 3 4 * 2 by hand, then verify with Python. Write out the step-by-step evaluation order.
Q2. Write code showing that not True or False and True evaluates differently than not (True or False) and True. Print both results.
Q3. Given x = 10, evaluate x > 5 and x < 20 or x == 0. Add parentheses to make the intent explicit. Test both versions.
Q4. Demonstrate right-to-left associativity: compute 2 3 2 and (2 3) 2. Print and explain the difference.
Q5. Write the formula for BMI: weight / height ** 2. Test with weight = 70, height = 1.75. Does Python evaluate it correctly without parentheses? Verify.
9. Short-Circuit Evaluation : Lazy Boolean Logic
Short-circuit evaluation means Python stops evaluating a boolean expression as soon as the result is determined. For and, if the left operand is falsy, the right is never evaluated. For or, if the left is truthy, the right is skipped.
# If x is 0, (10/x) is NEVER executed โ no error!
result = x != 0 and (10 / x) > 2
๐ผ Why Data Analysts Care
โข Safe access: if key in d and d[key] > 0: โ prevents KeyError
โข Guard clauses: if obj is not None and obj.value > 0: โ prevents AttributeError
โข Performance: Skip expensive checks when a cheaper one already determines the result
โ ๏ธ Side Effects
If the right operand has side effects (printing, modifying state), short-circuiting may silently skip them. Never rely on side effects in boolean expressions.
๐งช Concept Checks: Short-Circuit
Q1. Write code where and short-circuits to prevent a ZeroDivisionError. Use x = 0 and 10 / x. Print a message proving the division was skipped.
Q2. Write a function with a side effect (increments a counter). Show that False and side_effect() never calls the function. Print the counter.
Q3. Use or short-circuit to provide a default: config = user_config or default_config. Test with user_config = {} and user_config = None.
Q4. Write a guard clause: if lst is not None and len(lst) > 0: that safely handles lst = None. Show it prevents TypeError.
Q5. Demonstrate that True or print("hi") never prints, but False or print("hi") does. Explain why.
10. Walrus Operator (:=) : Assignment Expressions
Introduced in Python 3.8, the walrus operator := assigns a value to a variable as part of an expression. It eliminates the need to compute a value on one line and use it on the next.
# Before walrus
data = get_data()
if data:
process(data)
# After walrus
if (data := get_data()):
process(data)
๐ผ Why Data Analysts Care
โข Loop optimization: Avoid calling expensive functions twice in while-loops
โข List comprehensions: Filter and transform in one pass: [y for x in data if (y := transform(x)) > 0]
โข Inline validation: if (n := len(data)) > 100: print(f'{n} records')
โ ๏ธ Readability
The walrus operator can reduce readability if overused. Only use it when it genuinely eliminates redundancy.
๐งช Concept Checks: Walrus
Q1. Rewrite this using the walrus operator: n = len(data); if n > 5: print(n). Test with data = [1,2,3,4,5,6].
Q2. Use := in a while loop: read from a list until you find a negative number. Print each positive number as you go.
Q3. Use := in a list comprehension to filter and transform: from [1,2,3,4,5], keep only values where x**2 > 10. Print the squares.
Q4. Use := with re.search to extract and print the first email address from text = "Contact us at info@company.com for details".
Q5. Write code comparing the readability of a 4-line pattern vs walrus operator. When is walrus helpful vs harmful? Add comments explaining.
๐ ๏ธ Professional Practice Tasks
Theory is useless without muscle memory. Complete these tasks to solidify your understanding.
Task 1 (Expression Evaluator): Write a function evaluate(a, op, b) that takes two numbers and an operator string ('+', '-', '', '/', '//', '%', '*') and returns the result. Handle division by zero gracefully. Test all 7 operators.
Task 2 (Grade Classifier): Given score = 78, use chained comparisons and logical operators to classify: A(90+), B(80-89), C(70-79), D(60-69), F(<60). Print the grade with an f-string.
Task 3 (Bit Counter): Use % and // operators to count how many digits are in a number n = 123456. Also compute the sum of its digits. No string conversion allowed.
Task 4 (Leap Year Checker): Write a leap year checker using logical operators: divisible by 4 AND (not divisible by 100 OR divisible by 400). Test with: 2000, 1900, 2024, 2023.
Task 5 (Bill Splitter): Given total = 156.75, num_people = 4, tip_pct = 0.18, compute: tip amount, total with tip, per-person share (rounded to 2 decimal places). Print a formatted receipt.
๐ป Pure Coding Interview Questions
Q1.
Write a function is_power_of_two(n) using only bitwise operators (no loops, no log). Hint: n & (n-1) == 0. Handle edge cases.
Q2.
Write code to check if a number is even using: (a) modulo, (b) bitwise AND, (c) integer division. Show all three return the same result.
Q3.
Write a function clamp(value, min_val, max_val) that restricts a value to a range. Use min() and max(). Test edge cases.
Q4.
Write code demonstrating operator overloading: create a class where + concatenates strings with a separator.
Q5.
Write a function evaluate(a, op, b) that takes an operator as a string and returns the result. Handle division by zero.
Q6.
Write code using only bitwise operators (&,|,^,~,<<,>>) to: (a) multiply by 2, (b) divide by 2, (c) check if odd.
Q7.
Write a function compare_floats(a, b, tolerance=1e-9) that correctly handles floating-point comparison. Test with 0.1+0.2 vs 0.3.
Q8.
Write code that computes ab % m efficiently for large numbers using Python's pow(a, b, m). Compare with naive (ab) % m.
Q9.
Write a function digital_root(n) that repeatedly sums digits until single digit: 493 โ 16 โ 7. Use only arithmetic operators.
Q10.
Write code demonstrating short-circuit evaluation: create a function with a side effect and show and/or skip it when appropriate.
Q11.
Write a function negate_without_minus(n) that returns -n without using -. Hint: ~n + 1 (two's complement).
Q12.
Write a function abs_without_abs(n) using only comparison and arithmetic operators. No abs() built-in.
Q13.
Write code demonstrating all 6 comparison operators with a custom class by implementing eq, lt, etc. on a Temperature class.
Q14.
Write a function count_set_bits(n) that counts the number of 1-bits in binary representation using & and >> in a loop.
Q15.
Write a function is_palindrome_number(n) using only arithmetic operators to reverse digits and compare. No string conversion.
Q16.
Write code showing the ternary operator for 2 and 3 categories. Then write a nested ternary for grade classification.
Q17.
Write a function gcd(a, b) using only modulo and assignment (Euclidean algorithm). Test with several number pairs.
Q18.
Write code that computes n! (factorial) using functools.reduce and the * operator. Compare with math.factorial.
Q19.
Write a function round_to_nearest(value, step) that rounds to nearest multiple: round_to_nearest(17, 5) โ 15.
Q20.
Write code demonstrating // floor division with negative numbers: -7 // 2. Explain floor vs truncation division.
Q21.
Write a function safe_divide(a, b) returning (quotient, remainder) tuple. Handle: zero division, type errors, negatives.
Q22.
Write code using walrus operator to simplify: compute a value and use it in the same expression. Show before/after.
Q23.
Write a function matrix_scalar_ops(matrix, scalar, op) that applies +,-,*,/ between a 2D list and a scalar.
Q24.
Write a function chained_comparison(x, ranges) where ranges is [(0,10,'low'),(10,50,'mid'),(50,100,'high')]. Return label.
Q25.
Write a simple expression evaluator: parse and compute '3 + 4 * 2 - 1' respecting operator precedence.
๐ Day 2 Executive Summary
| # | Topic | Key Takeaway | Professional Application |
|---|---|---|---|
| 1 | Arithmetic | / always float; // floor; % remainder; ** power | Financial calculations, metrics |
| 2 | Assignment | +=, -= modify in-place (except immutables) | Running totals, counters |
| 3 | Comparison | == value; is identity; chaining supported | Data filtering, validation |
| 4 | Logical | and/or return values, not booleans | Multi-condition filters |
| 5 | Identity | is checks memory, in checks membership | Null checks, lookups |
| 6 | Bitwise | Binary-level manipulation of integers | Flags, performance tricks |
| 7 | Ternary | Inline if-else expression | Compact conditional logic |
| 8 | Precedence | * > / > +- > comparisons > not > and > or | Correct formula translation |
| 9 | Short-Circuit | and/or stop early when result is known | Safe access, guard clauses |
| 10 | Walrus := | Assign inside expressions (Python 3.8+) | Loop optimization |
โ Instructor's End-of-Day Checklist
โข [ ] I understand the difference between / (true division) and // (floor division).
โข [ ] I know that and/or return actual values, not just True/False.
โข [ ] I can use is vs == correctly (identity vs equality).
โข [ ] I understand operator precedence and use parentheses for clarity.
โข [ ] I can leverage short-circuit evaluation for safe access patterns.
โข [ ] I have completed all 5 practice tasks.
โข [ ] I have reviewed all 25 interview questions.