How to Add Fractions in Python

To add fractions in Python, import the Fractions module, pass each fraction component to the Fraction function as arguments then add the fraction objects together.

 

Here is an example of adding 1/2 and 1/4 together:

 

from fractions import Fraction

result = Fraction(1,2) + Fraction(1,4)

print(result)
3/4

 

We get the answer 3/4.

 

You don't have to supply the fraction components as arguments. You could just supply formatted fraction strings and the Fractions function will do the leg work:

 

from fractions import Fraction

result = Fraction('1/2') + Fraction('1/4')

print(result)
3/4