Math using Python 2

Hi! I tried to do the following math using Python 2, but it doesn’t work.

5/6 + 2/6

The way I solved it was:

a = 5/6
b = 2/6
c = a + b
print c

I reviewed my code and it seems correct. Why is the result 0? How do we add fractions in Python 2, then?

In Python 2, fractions divide in integers. Floats are truncated, so 5 / 6 is zero, and 2 / 6 is zero.

We don’t have this issue in Python 3, but in version 2 we just have to make sure that one of the operands is a float. Note the dot, below:

5 / 6.

2 / 6.

Similar to how we do it on paper… Add the numerators when the denominators are the same. 2 / 6 + 5 / 6 = 7 / 6

However it is not that simple unless we can parse out the numerators and denominators. It can be a lot of work.

In maths we learn that any real number with repeating decimal fraction can be shown as a rational number (a fraction, as it were).



1 + 1 / 6

It’s an interesting concept but it takes learning and a good bit of logic so add it to your special projects list for later on down the road. The topic did come up a few years back, maybe in a challenge or in the Town Square.

We have a tool in Python, the fractions module, which gives us the Fraction class. This gives us ways to add, subtract, multiply and divide fractions. Given their nature, the result is always another fraction, right? Makes this module a no-brainer to do the heavy lifting with fractions in Python.

>>> from fractions import Fraction
>>> pi = Fraction(22, 7)
>>> e = Fraction(19, 7)
>>> pi + e
Fraction(41, 7)

What science will be needed to find that missing 1?

>>> Fraction(6, 7) * Fraction(7, 6)
Fraction(1, 1)
>>> int(Fraction(1, 1))