There are a lot of posts with similar questions but even after going through them, I am unable to get the logic behind. Sorry, I have never programmed before. Below are two pieces of code - a recursive function for calculating the factorial. This gets an error 'local variable 'f' referenced before assignment' whether I pass 1 or any value.
def func(n):
if n != 1:
f = n*func(n-1)
else:
return f
However, when I change the code to:
def func(n):
if n == 1:
return 1
else:
f = n*func(n-1)
return f
there's no error and the program runs. In both cases, I have not initialized the variable 'f' before assigning and both are local to the function only. Just trying to get my basic concepts cleared. Thanks.