โณ Loading Python Engine...

๐Ÿ“Š 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

#CategoryOperatorsCore Use Case
1Arithmetic+, -, , /, //, %, *Numeric computations
2Assignment+=, -=, *=, /=, etc.In-place modification
3Comparison==, !=, <, >, <=, >=Filtering & validation
4Logicaland, or, notBoolean logic
5Identity & Membershipis, inObject inspection
6Bitwise&, `\, ^, ~, <<, >>`Binary manipulation
7Ternaryx if cond else yInline conditionals
8Precedence(evaluation order)Correct formula design
9Short-Circuitand/or early exitSafe access patterns
10Walrus:=Assignment expressions

1. Arithmetic Operators : Numeric Operations

๐Ÿ” What is it?

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:

OperatorNameExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/True Division7 / 32.333...
//Floor Division7 // 32
%Modulo7 % 31
**Power2 ** 101024

๐Ÿ’ผ 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.

In [ ]:

๐Ÿงช Concept Checks: Arithmetic

Q1. Compute 17 // 5 and 17 % 5. Verify: 5 * (17//5) + (17%5) == 17. Print all values and the verification.

In [ ]:

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.

In [ ]:

Q3. Given x = -7 and y = 2, compute x / y, x // y, and x % y. Explain why x // y is -4 and not -3.

In [ ]:

Q4. Write code to extract the tens digit from n = 4567 using only // and % operators. Print the result.

In [ ]:

Q5. Compute 232 and (23)2. Print both results and explain why they differ (right-to-left associativity).

In [ ]:

2. Assignment Operators : In-Place Operations

๐Ÿ” What is it?

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.

OperatorEquivalentExample
x += 5x = x + 5Accumulate totals
x -= 3x = x - 3Decrease counters
x *= 2x = x * 2Scale values
x //= 4x = x // 4Integer reduction
x **= 2x = x ** 2Square 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.

In [ ]:

๐Ÿงช Concept Checks: Assignment

Q1. Start with balance = 1000. Apply these in order: += 500, -= 200, *= 1.1, //= 1. Print balance after each step.

In [ ]:

Q2. Write a loop that computes n! (factorial) for n = 10 using only *=. Print the result and verify with math.factorial(10).

In [ ]:

Q3. Create text = "Hello". Use += to append " World". Then check if id(text) changed (proving a new object was created). Print both IDs.

In [ ]:

Q4. Start with x = 256. Apply //= 2 repeatedly in a loop until x < 1. Count and print how many iterations it took.

In [ ]:

Q5. Write code that uses %= to keep an angle within 0-359 degrees. Test with angle = 750. Print the normalized angle.

In [ ]:

3. Comparison Operators : Relational Logic

๐Ÿ” What is it?

Comparison operators evaluate two values and return a bool (True or False). Python supports: ==, !=, <, >, <=, >=. A unique Python feature is chained comparisons: 1 < x < 10.

OperatorMeaningExample
==Equal to5 == 5 โ†’ True
!=Not equal5 != 3 โ†’ True
<Less than3 < 5 โ†’ True
>Greater than5 > 3 โ†’ True
<=Less or equal5 <= 5 โ†’ True
>=Greater or equal6 >= 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.

In [ ]:

๐Ÿงช 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.

In [ ]:

Q2. Write a chained comparison that checks if temperature = 37.5 is in the "normal" range (36.1 to 37.2). Print the result.

In [ ]:

Q3. Compare strings: "apple" < "banana", "Apple" < "apple". Print results and explain how Python compares strings (lexicographic, Unicode order).

In [ ]:

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.

In [ ]:

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?

In [ ]:

4. Logical Operators : Boolean Algebra

๐Ÿ” What is it?

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.

OperatorReturns True if...Short-circuits when...
andBoth operands are truthyLeft operand is falsy
orAt least one is truthyLeft operand is truthy
notOperand is falsyNever

๐Ÿ’ผ 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'.
In [ ]:

๐Ÿงช 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.

In [ ]:

Q2. Demonstrate short-circuit evaluation: write code where and prevents a ZeroDivisionError. Print a message proving the second operand was never evaluated.

In [ ]:

Q3. Write code showing that "hello" and 42 returns 42, while "" and 42 returns "". Explain why and/or return values, not booleans.

In [ ]:

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.

In [ ]:

Q5. Use or to set defaults: given user_name = "" and fallback = "Guest", compute display_name = user_name or fallback. Print the result.

In [ ]:

5. Identity & Membership : Object Inspection

๐Ÿ” What is it?
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).
OperatorPurposeExample
isSame object?x is None
is notDifferent objects?x is not None
inValue in container?'a' in 'abc' โ†’ True
not inValue 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.

In [ ]:

๐Ÿงช 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.

In [ ]:

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.

In [ ]:

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.

In [ ]:

Q4. Given d = {"x": 1, "y": 2}, demonstrate that in checks keys (not values): test "x" in d and 1 in d. Print results.

In [ ]:

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).

In [ ]:

6. Bitwise Operators : Binary-Level Control

๐Ÿ” What is it?

Bitwise operators work on the binary (base-2) representation of integers. Python supports: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).

OperatorNameExampleResult
&AND5 & 31
`\`OR`5 \3`7
^XOR5 ^ 36
~NOT~5-6
<<Left shift5 << 110
>>Right shift5 >> 12

๐Ÿ’ผ 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).
In [ ]:

๐Ÿงช 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.

In [ ]:

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.

In [ ]:

Q3. Write a function is_odd(n) using n & 1. Test with 5 numbers. Explain why this works at the binary level.

In [ ]:

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.

In [ ]:

Q5. Compute ~5 and explain why the result is -6. Relate it to two's complement: ~n = -(n+1).

In [ ]:

7. Ternary Operator : Inline Conditionals

๐Ÿ” What is it?

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.

In [ ]:

๐Ÿงช Concept Checks: Ternary

Q1. Given x = -5, use the ternary operator to compute abs_x (absolute value) without using abs(). Print the result.

In [ ]:

Q2. Write a ternary expression that returns "even" if n is even, "odd" otherwise. Test with n = 7 and n = 12.

In [ ]:

Q3. Use a nested ternary to classify temp = 35 as "Cold" (< 15), "Warm" (15-30), or "Hot" (> 30). Print the result.

In [ ]:

Q4. Write a ternary that sets discount = 0.2 if is_member else 0.05. Test with is_member = True and is_member = False.

In [ ]:

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.

In [ ]:

8. Operator Precedence : Order of Evaluation

๐Ÿ” What is it?

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.

PriorityOperatorsAssociativity
Highest**Right-to-left
~, +x, -x (unary)Right-to-left
*, /, //, %Left-to-right
+, -Left-to-right
<<, >>Left-to-right
<, <=, >, >=, ==, !=Left-to-right
notRight-to-left
andLeft-to-right
LowestorLeft-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.

In [ ]:

๐Ÿงช Concept Checks: Precedence

Q1. Evaluate 2 + 3 4 * 2 by hand, then verify with Python. Write out the step-by-step evaluation order.

In [ ]:

Q2. Write code showing that not True or False and True evaluates differently than not (True or False) and True. Print both results.

In [ ]:

Q3. Given x = 10, evaluate x > 5 and x < 20 or x == 0. Add parentheses to make the intent explicit. Test both versions.

In [ ]:

Q4. Demonstrate right-to-left associativity: compute 2 3 2 and (2 3) 2. Print and explain the difference.

In [ ]:

Q5. Write the formula for BMI: weight / height ** 2. Test with weight = 70, height = 1.75. Does Python evaluate it correctly without parentheses? Verify.

In [ ]:

9. Short-Circuit Evaluation : Lazy Boolean Logic

๐Ÿ” What is it?

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.

In [ ]:

๐Ÿงช 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.

In [ ]:

Q2. Write a function with a side effect (increments a counter). Show that False and side_effect() never calls the function. Print the counter.

In [ ]:

Q3. Use or short-circuit to provide a default: config = user_config or default_config. Test with user_config = {} and user_config = None.

In [ ]:

Q4. Write a guard clause: if lst is not None and len(lst) > 0: that safely handles lst = None. Show it prevents TypeError.

In [ ]:

Q5. Demonstrate that True or print("hi") never prints, but False or print("hi") does. Explain why.

In [ ]:

10. Walrus Operator (:=) : Assignment Expressions

๐Ÿ” What is it?

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.

In [ ]:

๐Ÿงช 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].

In [ ]:

Q2. Use := in a while loop: read from a list until you find a negative number. Print each positive number as you go.

In [ ]:

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.

In [ ]:

Q4. Use := with re.search to extract and print the first email address from text = "Contact us at info@company.com for details".

In [ ]:

Q5. Write code comparing the readability of a 4-line pattern vs walrus operator. When is walrus helpful vs harmful? Add comments explaining.

In [ ]:

๐Ÿ› ๏ธ 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.

In [ ]:

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.

In [ ]:

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.

In [ ]:

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.

In [ ]:

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.

In [ ]:

๐Ÿ’ป 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.

In [ ]:

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.

In [ ]:

Q3.

Write a function clamp(value, min_val, max_val) that restricts a value to a range. Use min() and max(). Test edge cases.

In [ ]:

Q4.

Write code demonstrating operator overloading: create a class where + concatenates strings with a separator.

In [ ]:

Q5.

Write a function evaluate(a, op, b) that takes an operator as a string and returns the result. Handle division by zero.

In [ ]:

Q6.

Write code using only bitwise operators (&,|,^,~,<<,>>) to: (a) multiply by 2, (b) divide by 2, (c) check if odd.

In [ ]:

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.

In [ ]:

Q8.

Write code that computes ab % m efficiently for large numbers using Python's pow(a, b, m). Compare with naive (ab) % m.

In [ ]:

Q9.

Write a function digital_root(n) that repeatedly sums digits until single digit: 493 โ†’ 16 โ†’ 7. Use only arithmetic operators.

In [ ]:

Q10.

Write code demonstrating short-circuit evaluation: create a function with a side effect and show and/or skip it when appropriate.

In [ ]:

Q11.

Write a function negate_without_minus(n) that returns -n without using -. Hint: ~n + 1 (two's complement).

In [ ]:

Q12.

Write a function abs_without_abs(n) using only comparison and arithmetic operators. No abs() built-in.

In [ ]:

Q13.

Write code demonstrating all 6 comparison operators with a custom class by implementing eq, lt, etc. on a Temperature class.

In [ ]:

Q14.

Write a function count_set_bits(n) that counts the number of 1-bits in binary representation using & and >> in a loop.

In [ ]:

Q15.

Write a function is_palindrome_number(n) using only arithmetic operators to reverse digits and compare. No string conversion.

In [ ]:

Q16.

Write code showing the ternary operator for 2 and 3 categories. Then write a nested ternary for grade classification.

In [ ]:

Q17.

Write a function gcd(a, b) using only modulo and assignment (Euclidean algorithm). Test with several number pairs.

In [ ]:

Q18.

Write code that computes n! (factorial) using functools.reduce and the * operator. Compare with math.factorial.

In [ ]:

Q19.

Write a function round_to_nearest(value, step) that rounds to nearest multiple: round_to_nearest(17, 5) โ†’ 15.

In [ ]:

Q20.

Write code demonstrating // floor division with negative numbers: -7 // 2. Explain floor vs truncation division.

In [ ]:

Q21.

Write a function safe_divide(a, b) returning (quotient, remainder) tuple. Handle: zero division, type errors, negatives.

In [ ]:

Q22.

Write code using walrus operator to simplify: compute a value and use it in the same expression. Show before/after.

In [ ]:

Q23.

Write a function matrix_scalar_ops(matrix, scalar, op) that applies +,-,*,/ between a 2D list and a scalar.

In [ ]:

Q24.

Write a function chained_comparison(x, ranges) where ranges is [(0,10,'low'),(10,50,'mid'),(50,100,'high')]. Return label.

In [ ]:

Q25.

Write a simple expression evaluator: parse and compute '3 + 4 * 2 - 1' respecting operator precedence.

In [ ]:

๐Ÿ“Š Day 2 Executive Summary

#TopicKey TakeawayProfessional Application
1Arithmetic/ always float; // floor; % remainder; ** powerFinancial calculations, metrics
2Assignment+=, -= modify in-place (except immutables)Running totals, counters
3Comparison== value; is identity; chaining supportedData filtering, validation
4Logicaland/or return values, not booleansMulti-condition filters
5Identityis checks memory, in checks membershipNull checks, lookups
6BitwiseBinary-level manipulation of integersFlags, performance tricks
7TernaryInline if-else expressionCompact conditional logic
8Precedence* > / > +- > comparisons > not > and > orCorrect formula translation
9Short-Circuitand/or stop early when result is knownSafe access, guard clauses
10Walrus :=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.