How to Simplify Fractions in Python?

Estimated read time 1 min read

To simplify fractions in Python, you can use the fractions module, which provides a way to work with rational numbers and perform operations on fractions. Here’s an example of how to simplify a fraction in Python using the fractions module:

from fractions import Fraction

# Define the fraction to be simplified
f = Fraction(6, 8)

# Simplify the fraction
f_simplified = f.simplify()

# Print the result
print(f_simplified)  # 3/4

In this example, the Fraction class from the fractions module is used to create a fraction with a numerator of 6 and a denominator of 8. The simplify() method is then called on the fraction object to simplify it. The result is a new fraction object that represents the same value as the original fraction, but in simplified form. Finally, the result is displayed on the console using the print() function.

When you run this code, you will see the simplified fraction 3/4 displayed on the console, which is the result of dividing the numerator and denominator of the original fraction by their greatest common divisor. Note that you can use this technique to simplify any fraction, by creating a Fraction object with the numerator and denominator of the fraction, and calling the simplify() method on it.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply