Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting error message as Function name is not defined, new to python need help. Please

class Solution:
    def f(n):
        if n == 1 or n == 2:
            return 1
        fib1 = f(n-1)
        fib2 = f(n-2)
        out = fib1 + fib2
        return out
print(x)

Error message:-

Runtime Error
NameError: name 'f' is not defined
    x = f(2)
Line 1 in <module> (Solution.py)

I have tried to change the code and still the same response is there, i am new to programming and need help with the problem to clear my concept on calling function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The f(n) function is a method that belongs to the Solution class. Therefore, to use this method, you must initialize an object of the Solution class.

Furthermore, you are attempting to access the method from within itself. You should use the self keyword, as this will allow you to access class attributes and methods from within the class itself.

Overall, here is your code corrected. Make sure to take time to understand why your own code was wrong, and do further study on Object Orientated Programming (both in Python and in general). I wish you luck with future programming 🙂

class Solution:
    def f(self, n):
        if n == 1 or n == 2:
            return 1
        fib1 = self.f(n - 1)
        fib2 = self.f(n - 2)
        return (fib1 + fib2)


x = Solution()
print(x.f(6))  # outputs 8
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading