Search code examples
pythonloopsfactorial

Calculating a factorial using loops in Python3


I am currently studying Software Development as a beginner and I have a task in my programming class to calculate and display a factorial using a loop. I've been given the pseudo-code and have to translate it into true code and test it in the REPL to make sure it returns the expected results.

I almost have it but I've run into two issues that I just can't seem to resolve.

1) The function is returning an extra line of "None" after the calculation and

2) The answer is displaying over multiple lines when I want it to display on a single line.

My current code (which does return the correct answer) is as follows:

def calcFactorial(number):
    factorial = 1
    print(str(number)+"! =", number)
    for count in range (1, number):
        if number-count > 0:
            factorial = factorial*number-count
            print("x", str(number-count))
    factorial = factorial*number
    print("=", factorial)

When I test, using 3 for example, the REPL returns the following:

>>> print(calcFactorial(3))
3! = 3
x 2
x 1
= 12
None

So I have the correct answer but with an extra line of "None" which I would like to remove (I believe it has something to do with the print function?) and I don't know how to format it correctly. Any help would be much appreciated.


Solution

  • Your calcFactorial function does not explicitly return a value, so it would return None by default, so print(calcFactorial(3)) would always print None.

    You should make the calcFactorial function return factorial as a result at the end:

    def calcFactorial(number):
        factorial = 1
        print(str(number)+"! =", number)
        for count in range (1, number):
            if number-count > 0:
                factorial = factorial*number-count
                print("x", str(number-count))
        factorial = factorial*number
        print("=", factorial)
        return factorial