To get the Factorial of a number in Python using recursion, you have to use function, if statement and recursion login.
factorial of n is
A factorial is positive integer n, and denoted by n!. Then the product of all positive integers is less than or equal to n.
Factorial of 5 is:
5! = 1*2*3*4*5 = 120.
Example find Factorial of a number in Python using recursion
Simple example code Factorial of a number using recursion.
def foo(n): if n == 1: return n else: return n * foo(n - 1) num = 7 # check if the number is negative if num < 0: print("Use Positive numbers") elif num == 0: print("The factorial of 0 is 1") else: print("The factorial of", num, "is", foo(num))
User input value
def foo(n): if n == 1: return n else: return n * foo(n - 1) # taking input from the user number = int(input("User Input : ")) print("The factorial of", number, "is", foo(number))
User Input : 5
The factorial of 5 is 120
Do comment if you have any doubts or suggestions on this Python factorial program.
Note: IDE: PyCharm 2021.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.