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.
>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