Factorial Using Recursion in Python
Recursion in programming involves a function calling itself. A key application is calculating factorials in mathematics, where the factorial of a number is the product of all positive integers up to that number, denoted by an exclamation mark (e.g., 5!). Factorial of 3 (3!) is 6, as 3! = 3 * 2 * 1. Factorial of 0 is 1, with no factorial for negative integers.
In recursion, a factorial function repeatedly calls itself with a decrementing value. For instance, factorial(4) leads to factorial(3), factorial(2), and so on, until reaching 1. At 0, the function returns 1. The final result is the product of these calls, yielding the factorial.
Factorial of 0 is 1, and there is no factorial output for negative integers
Python Program to Find Factorial of Number Using Recursion
Below is the python program to calculate factorial using recursion for a number.
Output:
In the above program, factorial() is a recursive function that calls itself. Here, the function will recursively call itself by decreasing the value of the n (where n is the input parameter), i.e. n*factorial(n-1). A number is taken as input, and then if-else conditional statements are used to check whether that input number is valid or not, which means that the factorial using recursion function will be executed only if the input value given by the user is greater than or equal to 1.
Python Program to Find Factorial of Number Using Iterative method
Below is the python program to calculate the factorial of a number using For-Loop.
Output
Here, the number whose factorial is to be found is taken as input from the user and stored in num, and then we can check if the number is negative, zero or positive using an if-else statement. If the number is positive, we will use the for-loop and range() function to calculate the factorial. Else, the appropriate statement is printed.
Conclusion
- In a factorial using recursion program, the factorial function calls itself. Here, the function will recursively call itself by decreasing the value of the number.
- The factorial of 0 is 1, and there is no factorial output for negative integers.