Calculating the factorial of a number is a common operation in programming, and there are several ways to achieve it in Python. The factorial of a number is the product of all positive integers less than or equal to that number. For example, the factorial of 5 is 5! = 5 * 4 * 3 * 2 * 1 = 120.
In this article, we will explore different methods for calculating the factorial of a number in Python, including using a while
loop, a for
loop, recursion, and a class. These methods provide different approaches to solving the problem and offer varying levels of complexity.
How to find the factorial of a number in Python using while loop?
To find the factorial of a number in Python using a while loop, we can use the following code:
In the above example, the factorial_while()
function takes an integer n
as an argument and returns the factorial of n
using a while loop. It initializes a variable result
to 1 and then enters the loop, which runs as long as n
is greater than 1. Inside the loop, it multiplies result
by n
and decrements n
by 1. When the loop exits, it returns the value of result
.
Factorial of a number in Python using for loop
To find the factorial of a number in Python using a for loop, we can use the following code:
Python program to find factorial of a number using recursion
In the above Python program to find factorial of a number using recursion example, the factorial_recursion()
function takes an integer n
as an argument and returns the factorial of n
using recursion. It checks if n
is equal to 1 and, if so, returns 1. If n
is not equal to 1, it returns n
multiplied by the factorial of n-1
, which is calculated recursively.
Factorial program in Python using Class
Here’s an example of a class in Python that can calculate the factorial of a number:
Above example code for Factorial program in Python using Class defines a Factorial
class with a __init__
method to initialize the class with a number attribute, and a calculate
method to compute the factorial of that number. It then creates an instance of the Factorial
class with the number 5
and calls the calculate
method on it to print the result. The output will be 120
, which is the factorial of 5.
How to find factorial of a number in Python without using function?
You can find the factorial of a number in Python without using a function by using a loop and keeping track of the result in a variable. Here’s an example of How to find factorial of a number in Python without using function :
This will output 120
, which is the factorial of 5.