Factorial In Python

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 50:- Factorial In Python

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.

  1. 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

  1. 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: 120

In both examples, the function factorial_recursive() and factorial_loop() calculate the factorial of a given non-negative integer n. In the recursive approach, the function calls itself to calculate the factorial. In the loop approach, the function uses a for loop to iterate from 1 to n and continuously multiplies the result by the current value of i to 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 replace num with any non-negative integer to calculate its factorial.

6. Loops

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?