Python Basic Math and Number Tracing
Numerical arithmetic in Python includes floor division (`//`), modulo remainder (`%`), and exponentiation (`**`). Tracing negative number floor division and operator precedence rules (`PEMDAS`) is standard practice in coding interviews.
Core Conceptual Insights
Theoretical Blueprint:Floor division (`//`) always rounds down towards negative infinity (`the floor`), just like dropping a ball down a staircase: `-3.2` drops down to `-4`.
Common Developer Trap:Many programmers assume `-10 // 3` equals `-3`. Because `-10 / 3 = -3.333...`, rounding down towards negative infinity yields `-4`!
Structured Practice Breakdown
Floor division with negative numbers
print(-10 // 3, 10 // -3)
-4 -4Execution Walkthrough
Both `-10 // 3` and `10 // -3` compute `-3.333...`. In Python, `//` rounds down to the nearest lower integer (`the floor`), which is `-4`.
Modulo arithmetic with negative numbers
print(-10 % 3, 10 % -3)
2 -2Execution Walkthrough
`a // b` for `-10 // 3` is `-4`. Then `-10 - (3 * -4) = -10 - (-12) = 2`. For `10 % -3`: `10 - (-3 * -4) = 10 - 12 = -2`. Output: `2 -2`.
Right-associative exponentiation (`**`)
print(2 ** 3 ** 2)
512Execution Walkthrough
Because `**` is right-associative, `2 ** 3 ** 2` is grouped as `2 ** (3 ** 2) -> 2 ** 9 = 512`. (`If evaluated left-to-right, it would have been 8 ** 2 = 64`).
Unary minus and exponentiation precedence
print(-3 ** 2, (-3) ** 2)
-9 9Execution Walkthrough
Because `**` binds tighter than `-`, `-3 ** 2` computes `3 ** 2 = 9` first, then applies `-` to return `-9`. Parentheses `(-3) ** 2` force squaring `-3` directly: `9`.