Your Legal Resource

**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!
__

__Add two fractions:
__

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