0

I am new to python and I am stuck on how to get the below code to not receive an error when attempting to divide 2 fractions.

The error I receive is "TypeError: unsupported operand type(s) for //: 'Fraction' and 'Fraction'"

Any help would be appreciated.

#Defining GCD to be used for all aspects below
def gcd(m,n):
while m%n != 0:
    oldm = m
    oldn = n

    m = oldn
    n = oldm%oldn
return n

#Begining of Fraction Function
class Fraction:
def __init__(self,top,bottom):
    self.num = top
    self.den = bottom

def __str__(self):
    return str(self.num)+"/"+str(self.den)

def show(self):
    print(self.num,"/",self.den)

def __add__(self,otherfraction): #Addition of Fractions
    newnum = self.num*otherfraction.den + \
        self.den*otherfraction.num
    newden = self.den * otherfraction.den
    common = gcd(newnum,newden)
    return Fraction(newnum//common,newden//common)

def __sub__(self,otherfraction): #Subtraction of Fractions
    newnum = self.num*otherfraction.den - \
        self.den*otherfraction.num
    newden = self.den * otherfraction.den
    common = gcd(newnum,newden)
    return Fraction(newnum//common,newden//common)

def __mul__(self,otherfraction): #Multiplication of Fractions
    newnum = self.num*otherfraction.num
    newden = self.den * otherfraction.den
    common = gcd(newnum,newden)
    return Fraction(newnum//common,newden//common)

def __div__(self,otherfraction): #Division of Fractions
    newnum = self.num*otherfraction.den
    newden = self.den * otherfraction.num
    common = gcd(newnum,newden)
    return Fraction(newnum//common,newden//common)

def __eq__(self, other): #Equal Check
    firstnum = self.num * other.den
    secondnum = other.num * self.den
    return firstnum == secondnum

def main(): 
x = Fraction(1,2)
y = Fraction(2,3)

#Printing of solutions
print("The fractions are:",x,"and",y)
print("Adding the fractions equals:",x+y)
print("Subtracting the fractions equals:",x-y)
print("Multiplying the fractions equals:",x*y)
print("Dividing the fractions equals:",x//y)
print("Fraction x is equal to fraction y: ", x == y)
main()
MattDMo
  • 100,794
  • 21
  • 241
  • 231
pmac5
  • 65
  • 1
  • 7

0 Answers0