使用Python中的函数的一个数的因子 [英] Factorial of a number using function in Python

查看:263
本文介绍了使用Python中的函数的一个数的因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个问题是关于阶数的问题。使用功能



def f(n):

如果n == 0:

r = 1

else:

r = n * f(n-1)

返回r

print('答案是: ',r)

f(0)





这里有什么问题?



错误告诉我:

-------------------------- -------------------------------------------------

NameError Traceback(最近一次调用最后一次)

< ipython-input-68-cc9d7ecb020e>在< module>()

6 r = n * f(n-1)

7返回r

----> ; 8打印('Ans。是:',r)

9 f(0)



NameError:名称'r'未定义



我的尝试:



另一个是关于阶数的问题。使用函数

def f(n):
如果n == 0:
r = 1
else:
r = n * f(n-1 )
返回r
打印('Ans。是:',r)
f(0)


这里有什么问题?

错误告诉我:
-------------------------------- -------------------------------------------
NameError Traceback(最近的呼叫最后一次)
< ipython-input-68-cc9d7ecb020e> in< module>()
6 r = n * f(n-1)
7 return r
----> 8打印('Ans。是:',r)
9 f(0)

NameError:名称'r'未定义

解决方案

1 - 你应该研究范围的概念。

2 - 看起来像你的作业。如果您不愿意解决一个简单的问题,那么,当您遇到问题时,您认为以后会怎么做?



学习如何调试你的工作。



此外,上面的1是你问题的答案 - 你需要了解原因。


你有一个 print 语句试图引用一个不存在的变量。您必须先调用函数并捕获其返回值,然后才能打印它。


与其他指出的一样,您正在尝试访问超出范围的变量。尝试

  def  f(n):
if n == 0:
r = 1
else
r = n * f(n- 1
return r

print ' Ans。是:',f( 5 ))


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

解决方案

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.


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.


Like the others pointed out, you are trying to access a variable which is out of scope. Try

def f(n):
  if n==0:
    r=1
  else:
    r=n*f(n-1)
  return r

print('Ans. is:',f(5))


这篇关于使用Python中的函数的一个数的因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆