# Dealing with fractions in Python

Tyler (285)
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
67 guides
code
68 guides

## 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.

## 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.

## 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)``````

## 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'``````

## 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``````

## 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.

Calling all writers!

We're hiring. Write for Howchoo

Tyler
Joined in 2015
Software Engineer and creator of howchoo.
Related to this guide:
Get the latest edition of Python in just minutes.
Ash
In these interests: codewindowspython
Run Python scripts in command prompt without typing the whole path.
Ash
In these interests: windowscodepython
You can run any Python script in a command-line interface.
Ash
In these interests: python
Got a Python question? We've probably answered it here.
Not sure what version of Python you’re running? Time to find out!
Python is a very popular programming language for data visualization.
In Python, comprehensions are a useful construct that allows us to create new sequences in a very concise way.
Slack has become one of the most important tools for communication in many companies, mine included.
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.
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 in Python can be extremely powerful and save you from bloated and confusing initialization code.
Posted in these interests:
python
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 is poetry -- one line at a time.
Discuss this guide:
We're hiring!
Are you a passionate writer? We want to hear from you!

Follow @howchoo and learn cool things:

Like what we do?

Want to support Howchoo? When you buy a tool or material through one of our Amazon links, we earn a small commission as an Amazon Associate.