Click here to Skip to main content
15,896,557 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Another is that problem on factorial of a no. using function

def f(n):
if n==0:
r=1
else:
r=n*f(n-1)
return r
print('Ans. is:',r)
f(0)


what is problem here?

Error is showing me that:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-68-cc9d7ecb020e> in <module>()
6 r=n*f(n-1)
7 return r
----> 8 print('Ans. is:',r)
9 f(0)

NameError: name 'r' is not defined

What I have tried:

Another is that problem on factorial of a no. using function

def f(n):
    if n==0:
        r=1
    else:
        r=n*f(n-1)
    return r
print('Ans. is:',r)
f(0)


what is problem here?

Error is showing me that:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-68-cc9d7ecb020e> in <module>()
      6         r=n*f(n-1)
      7     return r
----> 8 print('Ans. is:',r)
      9 f(0)

NameError: name 'r' is not defined
Posted
Updated 20-Nov-18 3:40am

1 - You should look into the concept of scope.
2 - seems like your homework. If you aren't willing to work on an easy problem, now, what do you think you'll do later on when problems are difficult?

Learn how to debug your work.

Also, "1", above, is the answer to your problem - you need to learn why.
 
Share this answer
 
You have a print statement that is trying to reference a variable that does not exist. You must call your function and capture its return value before you can print it.
 
Share this answer
 
Like the others pointed out, you are trying to access a variable which is out of scope. Try
Python
def f(n):
  if n==0:
    r=1
  else:
    r=n*f(n-1)
  return r

print('Ans. is:',f(5))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900