Home > OS >  Why is my add function not giving me the correct output?
Why is my add function not giving me the correct output?

Time:05-15

I was trying to learn how to create classes in python and I wrote the following code to create a class called fraction. However, when I try to add two fractions, I don't get the correct output. Can someone tell me where I might have gone wrong?

class fraction:
  def __init__(self,top,bottom):
    self.num=top
    self.den=bottom

  def show(self):
    print(f"{self.num}/{self.den}")

  def __str__(self):
    return f"{self.num}/{self.den}"
    
  def __add__(self,other_fraction):
    new_num=self.num*other_fraction.den self.den other_fraction.num
    new_den=self.den*other_fraction.den
    return fraction(new_num,new_den)

Fraction I tried to add are 1/4 and 2/4

print(fraction(1,4) fraction(2,4))

Output I got: 10/16

Expected output:12/16

CodePudding user response:

You had a small typo (a that should have been a *).

class Fraction:
    def __init__(self, top, bottom):
        self.num = top
        self.den = bottom

    def show(self):
        print(self)  # this automatically calls self.__str__()!

    def __str__(self):
        return f"{self.num}/{self.den}"
        
    def __add__(self, other):
        new_num = self.num * other.den   other.num * self.den
        new_den = self.den * other.den
        return Fraction(new_num, new_den)

(Fraction(1, 4)   Fraction(2, 4)).show()  # 12/16
  • Related