# Dealing with fractions in Python

Tyler (270)
0

You may not need to deal with fractions often, but when you do Python's Fraction class comes to the rescue. In this guide I'll provide some interesting examples showing how to deal with fractions and highlighting some of the cool features.

Posted in these interests:

python
PRIMARY
61 guides
code
65 guides
1

## The basics

The fraction class is found in Lib/fractions.py so to import:

``from fractions import Fraction``

There are a number of ways to instantiate the Fraction class. First, you can pass in the numerator and the denominator.

``````>>> Fraction(1, 2)
Fraction(1, 2)``````

Or instantiate with another fraction:

``````>>> f = Fraction(1, 2)
>>> Fraction(f)
Fraction(1, 2)``````

Instantiate with a float:

``````>>> Fraction(2.5)
Fraction(5, 2)``````

Or with a decimal:

``````>>> from decimal import Decimal
>>> Fraction(Decimal('1.1'))
Fraction(11, 10)``````

Lastly, and probably the most interesting - you can instantiate with a string:

``````>>> Fraction('9/16')
Fraction(9, 16)``````

Ultimately, the Fraction class is designed so that there is very little processing you have to do before instantiating the class. It knows how to deal with multiple data types.

2

## Automatically reduces

Reducing isn't that hard, but for some complicated fractions it can take a few steps. The Fraction class is especially helpful because it automatically reduces your fraction.

``````>>> Fraction(153, 272)
Fraction(9, 16)``````

You might not be able to reduce 153/172 in your head, but the Fraction class will do it quickly.

3

## Binary operations

You can perform binary operations on a Fraction just like you can ints or floats!

``````>>> Fraction(1, 2) + Fraction(3, 4)
Fraction(5, 4)``````

So that's pretty great, but you can also mix in integers or floats. But as you might expect - adding an integer returns a Fraction object while adding a float returns a float.

``````>>> Fraction(5, 16) + 3
Fraction(53, 16)
>>> Fraction(5, 16) + 3.0
3.3125``````

Here are some examples of other binary operations:

``````>>> Fraction(5, 16) - Fraction(1, 4)
Fraction(1, 16)
>>> Fraction(1, 16) * Fraction(3, 16)
Fraction(3, 256)
>>> Fraction(3, 16) / Fraction(1, 8)
Fraction(3, 2)``````

Now let's try with exponentiation:

``````>>> Fraction(1, 8) ** Fraction(1, 2)
0.3535533905932738``````

It returns a float probably because the fraction is impossible to calculate within reason. We can actually use the limit_denominator method to get a semi-accurate Fraction as a result.

``````>>> f = Fraction(1, 8) ** Fraction(1, 2)
>>> Fraction(f).limit_denominator()
Fraction(235416, 665857)``````

Keep in mind you can mix in strings and other data types upon instantiation:

``````>>> Fraction("1/2") + Fraction(2.0)
Fraction(5, 2)
>>> Fraction(2) * Fraction("          1/2    ")
Fraction(1, 1)``````
4

## Accessing the attributes of a Fraction

So you've got a Fraction and you've done some calculations, now how do we access the attributes?

Without reading the documentation you might try Fraction.numerator and Fraction.denominator and you'd be right.

``````>>> f = Fraction(221, 234) + Fraction(1, 2)
>>> f.numerator
13
>>> f.denominator
9``````

Or print the entire fraction as a string:

``````>>> print f
13/9
>>> a = str(f)
>>> a
'13/9'``````
5

## GCD

This isn't part of the Fraction class, but it can be found in the fractions library. You can quickly find the greatest common divisor of two numbers.

First the import:

``from fractions import gcd``

And some examples:

``````>>> gcd(100, 75)
25
>>> gcd(221, 234)
13``````
6

## Conclusion

Hopefully you've learned something about dealing with fractions in Python. If you want to read more check out the docs. And if you're feeling extremely motivated check out the source.

Let me know if you've used fractions in a more interesting way. I'll add them to the guide.

Tyler
Joined in 2015
Software Engineer and creator of howchoo.
Related to this guide:
In Python, comprehensions are a useful construct that allows us to create new sequences in a very concise way.
Tyler
In these interests: codepython
Slack has become one of the most important tools for communication in many companies, mine included.
Tyler
In these interests: slackpython
If you're familiar with Python's keyword-only arguments, then you've probably wondered why the same constraint doesn't exist for positional arguments. This changes with Python 3.
Tyler
In these interests: codepython
Specify a parallel filesystem cache for compiled bytecode
AKA the Walrus Operator
Learn how to use formatted string literals in Python
While this requirement may seem rare, learning how to nest defaultdicts properly can be extremely powerful and save you from bloated and confusing initialization code.
In Python, we often run into scenarios where we need to merge two or more lists. This is also called list concatenation, and Python provides multiple methods for accomplishing this.
Find and fix slow running Python unit tests
In Python, range is an immutable sequence type, meaning it's a class that generates a sequence of numbers that cannot be modified.
Posted in these interests:
python
61 guides 105 subscribers
PRIMARY
Python is howchoo's favorite programming language. We believe python promotes the most organized and performant codebase possible. We also love Django so, naturally, we love Python.
code
65 guides 98 subscribers
Code is poetry -- one line at a time.
Discuss this guide:
Follow @howchoo and learn cool things!