bhylu.com

Advertisements

Numbers

Python offers integers, floating-point values, and complex numbers. Choose a representation that matches the calculation rather than treating every number as interchangeable.

Understand the idea

Integers have arbitrary precision within available memory. Floats use binary approximation, so some decimal fractions are not stored exactly. For exact decimal financial rules, use Decimal with text inputs or a carefully defined integer-minor-unit model. Complex numbers have real and imaginary components for suitable mathematical work.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

from decimal import Decimal
print(0.1 + 0.2 == 0.3)
print(Decimal("0.1") + Decimal("0.2"))

Read the result

The float comparison is False, while the Decimal sum displays 0.3. The difference comes from representation, not a random arithmetic failure.

Try one change

Compare a float calculation with math.isclose, then explain why an exact equality check can be the wrong test.