我需要一些功能方面的帮助 [英] I need a little bit of help with functions
本文介绍了我需要一些功能方面的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我似乎无法理解这段代码,它是关于数字的因素,但我不明白该功能是如何工作的,如果有人可以帮忙,我会很高兴。
def因子(x):
如果x == 0:
返回1
返回x *因子(x - 1)
x = int(输入())
打印(因子(x))
我的尝试:
只是理解........... .................................................. .......
Hello, I can't seem to understand this code, it's about factor a number but I don't understand how works the function, I would be glad if someone can help with this.
def factor(x):
if x==0:
return 1
return x * factor(x - 1)
x=int(input())
print (factor(x))
What I have tried:
Just understanding....................................................................
推荐答案
此函数计算数字x的阶乘。
请参阅:https://en.wikipedia.org/wiki/Factorial [ ^ ]
函数调用自身:它是一个递归函数。
请参阅: https://www.programiz.com/python-programming/recursion [ ^ ]
This function calculates the factorial of the number x.
Please see: https://en.wikipedia.org/wiki/Factorial[^]
The function calls itself: it's a recursive function.
Please see: https://www.programiz.com/python-programming/recursion[^]
最终x的值达到0(由于x-1指令)并停止调用自身(因子0)定义为1)。
整个函数也在我的第一个答案的第二个链接中解释。您还可以将函数编写为:
Eventually the value of x reaches 0 (because of the x-1 instruction) and stops calling itself (the factorial of 0 is defined as 1).
The whole function is also explained in the second link in my first answer. You can also write the function as:
def factor(x):
result = 1
while x > 0: # x > 1 will do
result = x * result
x = x - 1
return result
这篇关于我需要一些功能方面的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文