I have the following class. I have tried many basic examples but I always get the same error.

class Factorial(object):
    def calculate(self, n):
        if n == 0:
            return 0
        elif n == 1:
            return 1
        else:
            return n * calculate(self, n - 1)
        
if __name__ == "__main__":
    fact = Factorial()
    print fact.calculate(5)

When I run the code, it gives me the following error

line 8, in calculate
NameError: global name 'calculate' is not defined

. It seems that the recursive call cannot be executed because the function is somehow undefined. Every time I have to incorporate recursion in class' methods, I get this error. Am I missing a piece of code? Your help is greatly appreciated.

Change to return n * self.calculate(n - 1)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.