如何使用for循环计算阶乘并使用答案打印计算?

问题描述 投票:1回答:1

我正在尝试研究如何在Python中打印因子的完整细分,例如。 4 x 3 x 2 x 1 = 24。我被告知必须使用for循环。我不久前接近它,但后来做了一些愚蠢的事情并再次丢失了。

到目前为止,这是我的代码:

number = int(input("Please enter a number: "))
factorial = 1

for product in range(1, number + 1):
    if number > 0:
        factorial = factorial * number
        number = number - 1
    print(product, "x", number, "\t= ", factorial)
python for-loop factorial
1个回答
2
投票

您可以执行以下操作:

number = int(input("Please enter a number: "))
factorial = 1
for product in range(number, 1, -1):
    factorial *= product
    print(product, 'x', end=' ')
print(1, '=', factorial)
© www.soinside.com 2019 - 2024. All rights reserved.