In this tutorial, we will learn how to write a program to calculate the factorial of a number in Python. We will cover the basics of using a loop to compute the factorial.
The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n! and is calculated as n! = n × (n-1) × (n-2) × ... × 1. The factorial of 0 is 1.
The syntax to calculate the factorial in Python is:
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
We can use a loop to calculate the factorial of a number.
For example,
factorial
that takes one parameter n
.result
to 1.for
loop to iterate from 1 to n
(inclusive).result
by the current number in the loop.result
after the loop ends.factorial
function with the desired number and print the result.def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
# Calculate the factorial of 5
print(factorial(5))
120