CBSE Class 12 Computer Science Question 29 of 56

Functions — Question 29

Back to all questions
29
Question

Question 25

Write a Python function to calculate the factorial of a number (a non-negative integer). The function accepts the number whose factorial is to be calculated as the argument.

Solution
def factorial(n):
    product = 1
    for i in range(1, n + 1):
        product *= i
    return product

n = int(input("Enter a number: "))
fact = factorial(n)
print("The factorial of", n, "is", fact)
Output
Enter a number: 5
The factorial of 5 is 120.


Enter a number: 0
The factorial of 0 is 1.
Answer

def
factorial
(
n
):
product
=
1
for
i
in
range
(
1
,
n
+
1
):
product
*=
i
return
product
n
=
int
(
input
(
"Enter a number: "
))
fact
=
factorial
(
n
)
print
(
"The factorial of"
,
n
,
"is"
,
fact
)
Output
Enter a number: 5
The factorial of 5 is 120.


Enter a number: 0
The factorial of 0 is 1.