Fractions in Python 


               


Fractions in Python



Python


In this article, we explain fractions and how to code them in Python.

So, as you probably know, a fraction is a part of a whole number.

50% of a whole number is 1/2.

75% of a whole number is 3/4.

And so on.

How can we express fractions in Python?

To do so, we use the fractions module in Python.

The fractions module is part of the standard library in Python, so it already comes installed (you don't have to install it). So all that we have to do is import it.

In the code below, we create the fraction 3/4 (three-fourths).

We also show how to extract the numerator or denominator from a fraction.



So the first thing we have to do is import the Fraction class from the fractions module.

After this is done, we then create a variable, fraction1, and set it equal to, Fraction(1,4)

So fraction1 is now a fraction that has a value of 1/4 (0.25).

We then create another variable, fraction2, and set it equal to, Fraction(2,4)

fraction2 is now a fraction that has a value of 2/4 (0.5).

We then create another variable, total, which is the sum of fraction1 and fraction2.

Since 1/4 + 2/4= 3/4, total is a fraction equal to 3/4.

If you add a fraction to a decimal, a decimal will be output.

We add total with 1.25 and get a decimal of 2.0 (since 3/4 + 1.25=2.0).

If you want to get the numerator of a fraction, then you can use the numerator attribute.

If you want to get the denominator of a fraction, then you can use the denominator attribute.

This is shown in the code below.



So using the numerator and denominator attributes, we can extract either the numerator or denominator from a fraction in Python.

And this is most of the coding that you need to create and use fractions in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...