Factorial Calculation

Category: Python Basics
Tags:

Write a program that calculates the factorial of a number. This program should take as input a non-negative integer and output the factorial of that number.

Example:

Input: 5
Output: 120
Input: 0
Output: 1

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!. For example, 5! is 5*4*3*2*1 = 120. The factorial function can be defined by the product n! = n*(n-1)…321.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))  # Outputs: 120
print(factorial(0))  # Outputs: 1

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!