Python Program to Find Factorial of a Number | Using for loop, while loop & recursion

Python Program to Find Factorial of a Number | Using for loop, while loop & recursion

Python Program
The Factorial is the product of all numbers, which are less than or equal to that number, and greater than 0.

n! = n * (n-1) * (n -2) * …….* 1
For example, Factorial of 5 is represented as 5! = 5 *4 * 3 * 2 * 1 = 120

C Program to Find Factorial of a Number
Using for loop:

number = int(input("Please enter a Number to find factorial "))

fact = 1

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

    fact = fact * i

print("The factorial of %d = %d" %(number, fact))


Using while loop:

number = int(input("Please enter a Number to find factorial "))

fact = 1

i = 1

while(i <= number):

    fact = fact * i

    i = i + 1

print("The factorial of %d = %d" %(number, fact))


Using recursion:

def factorial(num):

    if((num == 0) or (num == 1)):

        return 1

    else:

        return num * factorial(num - 1)

number = int(input("Please enter a Number to find factorial "))

fact = factorial(number)

print("The factorial of %d = %d" %(number, fact))


Output:

Please Enter a number to Find Factorial 5

Factorial of 5 = 120

Please Enter a number to Find Factorial 10

Factorial of 10 = 3628800 


Run Code: 
If you want run this code copy this code, paste here and run.

No comments: