Codectionary / Developer documentation / Python

Exact Fractions

Fraction stores a reduced rational numerator and denominator, preserving exact ratios through arithmetic. A zero denominator raises ZeroDivisionError. Run as a Python 3.11+ script.

Syntax

Fraction(numerator, denominator)

Examples

Exact Fractions

Run as a Python 3.11+ script.

from fractions import Fraction
portion = Fraction(1, 3) + Fraction(1, 6)
print(portion)
print(portion.numerator, portion.denominator)
print(portion * 6)
  1. Expected output: 1/2 1 2 3
  2. The addition reduces to one half automatically. Multiplication stays rational even when its printed value is a whole number.

Best practices

  • Construct ratios from integers or decimal strings instead of approximate floats.
  • Convert to float only at a boundary that requires it.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading