Search code examples
pythonfor-loopfactorial

How to calculate a factorial using a for loop and print the calculation with the answer?


I'm trying to work out how to print the full breakdown of a factorial in Python, eg. 4 x 3 x 2 x 1 = 24. I have been instructed that I must use a for loop. I got close to it a while ago, but then did some stupid stuff and lost it again.

Here is my code so far:

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)

Solution

  • You could do the following:

    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)