Search code examples
pythonfactorial

Factorial function in Python with print function


def factorial(n):
   """Function to return the factorial
   of a number using recursion"""
   if n == 1:
       return n
   else:
       return n*factorial(n-1)

def main():
    for i in range(1,10):
        f = factorial(i)
        print(f'{i}! = {f}')

if __name__ == "__main__":
    main()

For the result I keep getting an error message that says "Invalid Syntax" where the print statement is.

I am creating a factorial function where I want the output to look like this:

 1!=1
 2!=2
 3!=6
 4!=24
 5!=120
 6!=720
 7!=5040
 8!=40320
 9!=362880

I have checking my code over and over to see of I have made any errors but I didn't detect any.


Solution

  • def factorial(n):
    """Function to return the factorial of a number using recursion"""
    if n == 1:
        return n
    else:
        return n*factorial(n-1)
    
    def main():
        print("NOTE: Parameter n has to be greater or equal to 1")
        n = int(input("Parameter 1: "))
        m = int(input("Parameter 2: "))
        print()
        for i in range(n,m):
            f = factorial(i)
            #print(f'{i}! = {f})
            print("{}! = {}".format(i, f))
    
     if __name__ == "__main__":
           main()