python - 理解 Python 中的阶乘

标签 python

我知道如何为一个数字的阶乘编写一个函数,但我不确定它为什么会起作用。

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/

相关文章:

python - 正则表达式匹配 'lol' 到 'lolllll' 和 'omg' 到 'omggg' 等

python - 如何将数据写入 Redshift,这是在 Python 中创建的数据框的结果?

python - "twin"matplotlib 中没有共享轴的轴

Python游戏结束屏幕不接受输入

Ubuntu 16.04 LTS 中的 Python 给出错误/lib/x86_64-linux-gnu/libc.so.6 版本 `GLIBC_2.25' 未找到

python - 自定义权重初始化 tensorflow tf.layers.dense

python - 如何为以下情况定义查询过滤器?

python - 安装到(非 root)用户帐户后如何找到 python 命令行工具?

python - 如何调整 QLabels 的大小以适合 QScrollArea 中的内容

python - 来自旧字典的新字典,将特定值与适当的键组合起来