MOD-05 · Sequence #5 · Python Basics

Python Numbers & Type Casting

Python integers have arbitrary precision (they never overflow into negative numbers). Floats follow IEEE 754 double precision. Understanding integer floor division (//), modulo (%), and explicit type casting is crucial for algorithmic problem solving.

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
a = int(2.8)    # 2
b = float(3)    # 3.0
c = str(42)     # '42'

Core Principles & Mental Models

1. Arbitrary Precision Integers

No 32-bit or 64-bit Overflow

  • In languages like C or Java, an int overflows at 2^31 - 1 or 2^63 - 1.
  • In Python 3, int objects have arbitrary precision; they automatically allocate as many digits in RAM as needed.
  • You can calculate 2**1000 or factorial(100) without any integer overflow errors.
big_int = 2 ** 128
print("2^128:", big_int)
print("Digit count:", len(str(big_int)))
💡 Key Takeaway: Python integers expand dynamically in memory and never suffer from classical buffer/integer overflow.

2. Floor Division (//) and Modulo (%)

Flooring Toward Negative Infinity

  • The single slash (/) always returns a float: 6 / 2 -> 3.0.
  • The double slash (//) performs floor division, rounding down towards negative infinity (not towards zero).
  • For positive numbers: 7 // 2 = 3. For negative numbers: -7 // 2 = -4 (floored down!).
  • Modulo (%) satisfies the identity: a = (a // b) * b + (a % b).
print("7 // 2 =", 7 // 2)      # 3
print("-7 // 2 =", -7 // 2)    # -4 (Floored toward -infinity!)
print("-7 % 2 =", -7 % 2)      # 1 (Because -4 * 2 + 1 = -7)
💡 Key Takeaway: Python floor division rounds towards -∞, making negative division results differ from C/C++ which truncates towards zero.

Interactive Walkthrough Examples

Floor Division & Modulo Rules (Basic)

Demonstrating division semantics with positive and negative dividends.

pairs = [(7, 3), (-7, 3), (7, -3), (-7, -3)]
for num, denom in pairs:
    q = num // denom
    r = num % denom
    check = (q * denom) + r == num
    print(f"{num:2} // {denom:2} = {q:2}, {num:2} % {denom:2} = {r:2} [Invariant Valid: {check}]")

Explanation: The mathematical division invariant always holds true in Python.

Common Misconceptions & Exam Traps

Common Pitfall: Floating Point Representation Imprecision

IEEE 754 floats cannot represent 0.1 in finite binary fractions, yielding a tiny representation error.

Buggy Code
total = 0.1 + 0.2
if total == 0.3:
    print("Equal")
else:
    print("Not equal:", total)  # 0.30000000000000004!
Correct Solution
import math
total = 0.1 + 0.2
if math.isclose(total, 0.3, rel_tol=1e-9):
    print("Safely Equal!")

Exam Trap Note: In exams, `0.1 + 0.2 == 0.3` evaluates to False. Always use math.isclose() or round() for float equality.

Conceptual Knowledge Self-Check Quiz

Q1: What is the result of the expression `-9 // 2` in Python?

  1. -4
  2. -5
  3. -4.5
  4. Error

-9 / 2 is -4.5. Floor division rounds down toward negative infinity, resulting in -5.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Use math.isclose() when comparing floating-point results.
  • ✅ Use the decimal module for financial calculations requiring exact precision.

All 26 Curriculum Modules