Ad Code

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

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

Code:

def factorial(n):

    # Check if n is negative

    if n < 0:

        return "Factorial is not defined for negative numbers"

    # Initialize factorial to 1

    fact = 1

    # Multiply factorial by each integer from 1 to n

    for i in range(1, n + 1):

        fact *= i

    return fact


# Example usage

if __name__ == "__main__":

    # Test the function with some sample inputs

    print("Factorial of 5:", factorial(5))

    print("Factorial of 0:", factorial(0))

    print("Factorial of 10:", factorial(10))


Reactions

Post a Comment

0 Comments