If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, you can calculate the factorial of a non-negative integer using a recursive function or a loop. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.
- Using Recursive Function:
pythonCopy code
def factorial_recursive(n): if n == 0 or n == 1: return 1 else: return n * factorial_recursive(n - 1) # Example usage: num = 5 result = factorial_recursive(num) print(f"The factorial of {num} is: {result}")Output:
csharpCopy code
The factorial of 5 is: 120
- Using Loop:
pythonCopy code
def factorial_loop(n): result = 1 for i in range(1, n + 1): result *= i return result # Example usage: num = 5 result = factorial_loop(num) print(f"The factorial of {num} is: {result}")Output:
csharpCopy code
The factorial of 5 is: 120In both examples, the function
factorial_recursive()andfactorial_loop()calculate the factorial of a given non-negative integern. In the recursive approach, the function calls itself to calculate the factorial. In the loop approach, the function uses aforloop to iterate from 1 tonand continuously multiplies the result by the current value ofito calculate the factorial.When you call either of the functions with
num = 5, it will calculate the factorial of 5, which is 120, and print the result. You can replacenumwith any non-negative integer to calculate its factorial.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform
Didn't find what you're looking for?
Contact Support