How to calculate the factorial of a number in Python
How to calculate the factorial of a number in Python.
Here's a detailed step-by-step tutorial on how to calculate the factorial of a number in Python.
Step 1: Understanding Factorial
Factorial is the product of an integer and all the integers below it. For example, the factorial of 5 (denoted as 5!) is calculated as: 5 x 4 x 3 x 2 x 1 = 120.
Step 2: Using a Loop to Calculate Factorial
One common way to calculate factorial is by using a loop. Here's an example of how you can do it in Python:
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
In this code, we define a function called factorial
that takes a single argument n
, which represents the number for which we want to calculate the factorial.
We initialize a variable called result
to 1, as the factorial of any number multiplied by 1 is equal to the number itself.
We then use a for
loop to iterate through the range from 1 to n+1
(inclusive). Inside the loop, we multiply the current value of result
by the loop variable i
, and update the value of result
accordingly.
Finally, we return the calculated factorial value stored in result
.
Step 3: Testing the Function
To test the factorial
function, you can call it with different numbers and print the returned value. Here's an example:
print(factorial(5)) # Output: 120
print(factorial(10)) # Output: 3628800
Step 4: Using Recursion to Calculate Factorial
Another approach to calculate factorial is by using recursion. Recursion is a technique where a function calls itself. Here's an example of how you can calculate factorial using recursion in Python:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
In this code, the factorial
function checks if the input n
is equal to 0. If it is, it returns 1, as the factorial of 0 is defined as 1.
If n
is not 0, the function calls itself with the argument n-1
and multiplies the result by n
. This process continues until n
becomes 0, and the function starts returning the calculated factorial values.
Step 5: Testing the Recursive Function
To test the recursive factorial
function, you can call it with different numbers and print the returned value. Here's an example:
print(factorial(5)) # Output: 120
print(factorial(10)) # Output: 3628800
That's it! You now know how to calculate the factorial of a number in Python using both a loop and recursion.