Python - Numbers & Casting
Overview
Estimated time: 25–35 minutes
Work with numeric types and safely convert between types.
Learning Objectives
- Use intandfloat; knowDecimalandFractionfor precision.
- Cast values with int(),float(), andstr()appropriately.
- Understand floating point pitfalls and when to prefer Decimal.
Prerequisites
Integers and floats
x = 7
y = 2
print(x / y)   # float division -> 3.5
print(x // y)  # floor division -> 3
print(x % y)   # modulo -> 1
print(2 ** 10) # exponentiation -> 1024
Casting
print(int("42"))      # 42
print(float("3.14"))  # 3.14
print(str(123))        # '123'
Precision with Decimal and Fraction
from decimal import Decimal, getcontext
from fractions import Fraction
print(0.1 + 0.2)                # 0.30000000000000004
print(Decimal("0.1") + Decimal("0.2"))  # 0.3
print(Fraction(1, 3) + Fraction(1, 6))   # 1/2
getcontext().prec = 4
print(Decimal(1) / Decimal(7))  # 0.1429 (with precision 4)
Common Pitfalls
- Comparing floats directly; use a tolerance or math.isclose.
- Constructing Decimalfrom a float; prefer string input to avoid binary rounding issues.
Checks for Understanding
- What’s the difference between /and//?
- Why use Decimal("0.1")instead ofDecimal(0.1)?
Show answers
- /is true division (float),- //is floor division.
- To avoid inheriting binary floating point rounding errors.
Exercises
- Compute monthly interest on a balance using Decimalto two decimal places.
- Sum 1/10ten times usingFractionand compare to float.