Search code examples
pythonfunctionclassaveragestatic-methods

How this code is failing to give me an accurate answer?


this is my code which is working fine but it is not correct. I am unable to figure out the problem

class MathUtils:

    @staticmethod
    def average(a, b):
        return a + b / 2

print(MathUtils.average(2, 1))


Solution

  • you made a tiny mistake - what your code actually does is taking b, dividing it by 2 and then add the result to a. so you get 2 + 0.5 = 2.5

    you need to put parentheses around a + b:

    class MathUtils:

    @staticmethod
    def average(a, b):
        return (a + b) / 2
    

    print(MathUtils.average(2, 1))