我知道如何为一个数字的阶乘编写一个函数,但我不确定它为什么会起作用。
def factorial (num):
ans = 1
for i in range (1,num + 1):
ans *= i
return (ans)
在我看来 ans 仍然是 1,并且乘以 1 到 nums + 1 上的每个索引。所以它看起来像:(1 * 1, 1 * 2, 1 * 3,...)。这个函数如何导致参数中数字的阶乘?
最佳答案
为什么不在你的代码中引入一些打印语句来看看发生了什么?
def factorial(num):
ans = 1
for i in range(1, num + 1):
print(f" ans = {ans}, going to multiply by {i}")
ans *= i
return ans
print("Trying to find the factorial of 5")
final = factorial(5)
print(f"Final answer is: {final}")
这给出:Trying to find the factorial of 5
ans = 1, going to multiply by 1
ans = 1, going to multiply by 2
ans = 2, going to multiply by 3
ans = 6, going to multiply by 4
ans = 24, going to multiply by 5
Final answer is: 120
所以最重要的是,您需要更好地了解 *=
正在做ans *= i
(又名就地运算符),请参见此处:https://docs.python.org/3/library/operator.html#in-place-operators
关于python - 理解 Python 中的阶乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63677765/