Search code examples
pythonfractions

How to get the nominator/denominator of a Fraction object


I have four variables that are added as fractions:

n1 = input("Denominator 1")
d1 = input("Denominator 1")
n2 = input("Denominator 1")
d2 = input("Denominator 1")

def fraction(n1,d1,n2,d2):
    a = Fraction(n1,d1)
    b = Fraction(n2,d2)
    print(a+b)
    return

fraction(n1,d1,n2,d2)

The answer comes out as something like 23/45.

How would I separate the two numbers and remove the divisor?

23
---
45

Solution

  • a = Fraction(n1, d1)
    b = Fraction(n2, d2)
    c = a+b
    print(c.numerator, c.denominator, sep="\n---\n")
    

    The next time that you'll need something like this, do dir(c)

    you'll get back something like:

     [..., '_sub', 'conjugate', 'denominator', 'from_decimal', 'from_float', 'imag', 'limit_denominator', 'numerator', 'real']
    

    (also, help(c) or looking at the documentation is useful)