How to Use Fractions Module in Python: Simple Guide
Use the
fractions module in Python by importing it and creating Fraction objects to represent rational numbers exactly. You can create fractions from integers, floats, or strings and perform arithmetic with them.Syntax
The fractions module provides the Fraction class to create rational numbers. You import it with from fractions import Fraction. Then, create a fraction using Fraction(numerator, denominator) or from a string like Fraction('3/4').
Key parts:
Fraction: class to represent fractionsnumerator: integer numeratordenominator: integer denominator (not zero)- Can also create from strings or floats
python
from fractions import Fraction # Create fraction from numerator and denominator f1 = Fraction(3, 4) # Create fraction from string f2 = Fraction('5/6') # Create fraction from float f3 = Fraction(0.5)
Example
This example shows how to create fractions, add them, and print the result as a fraction and a float.
python
from fractions import Fraction f1 = Fraction(1, 3) f2 = Fraction('2/5') result = f1 + f2 print('Sum as fraction:', result) print('Sum as float:', float(result))
Output
Sum as fraction: 11/15
Sum as float: 0.7333333333333333
Common Pitfalls
Common mistakes include:
- Using floats directly can cause precision issues because floats are approximate.
- Passing a float to
Fractionwithout converting can give unexpected results. - Denominator cannot be zero.
Always prefer creating fractions from strings or integers for exact values.
python
from fractions import Fraction # Wrong: float approximation problem f_wrong = Fraction(0.1) print('From float 0.1:', f_wrong) # Right: create from string for exact fraction f_right = Fraction('0.1') print('From string "0.1":', f_right)
Output
From float 0.1: 3602879701896397/36028797018963968
From string "0.1": 1/10
Quick Reference
Summary tips for using fractions module:
- Import with
from fractions import Fraction - Create fractions from integers, strings, or floats (prefer strings for exactness)
- Use arithmetic operators (+, -, *, /) directly on
Fractionobjects - Convert to float with
float()if needed - Denominator must not be zero
Key Takeaways
Import the fractions module and use Fraction to represent exact rational numbers.
Create fractions from strings or integers to avoid float precision errors.
You can do math directly with Fraction objects using normal operators.
Avoid creating fractions directly from floats unless you understand precision limits.
Convert fractions to float when you need approximate decimal values.