Site icon Codeforcoding

Find Factorial:Python program to using function

Python program to find factorial using function

In this tutorial, we will discuss the Python program to find factorial using function

In this program, we are going to learn about how to find  factorial using  the function in Python language

Factorial is a product of all positive descending integer begins with a specified number (n) and calculates up to one

Python program to find factorial using function

 

Example

factorial of 5 is

5!=5*4*3*2*1=120

 

factorial of 7 is

7!=7*6*5*4*3*2*1=5040

 

The factorial of a positive number n is given below

factorial of n is

n!=n*(n-1)*....2*1

In my previous post, I have explained the various ways to Find factorial of a number in Python

However, in this program, we embed the logic of the factorial program in the function

you can embed the logic of the factorial program to find the factorial of numbers using any of the following approaches in the function

The user can provide numbers as they wish and get the factorial according to their input

Program 1

Find factorial using Python function – using for loop

#Pyton program to find factorial of a number

def factorial(num):#function definition
    fact=1

    for i in range(1, num+1):#for loop for finding factorial
        fact=fact*i
    return fact    #return factorial 

number=int(input("Please enter any number to find factorial: "))

result=factorial(number)#function call and assign the value to variable result

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

 

When the above code is executed, it produces the following results

Please enter any number to find factorial: 6
The factorial of 6 = 720

 

Find factorial using Python function – using while loop

def factorial(num):#function definition
    
    fact=1;
    i=1
    while i<=num:
        fact=fact*i
        i=i+1
    return fact
    
num=input("Enter a number..");

result=factorial(num)

print("factorial of the number: %d" %result)

factorial(num)#function call

When the above code is executed, it produces the following results

Enter a number..5
factorial of the number: 120

 

Programming approaches for implementing these program

 

Check out these related examples

Java code to calculate the factorial of a number

Java code to calculate the factorial of a number using Java method

Calculate factorial of a number in C

Calculate factorial of a number in CPP

Calculate factorial of a number in Python

Calculate  factorial of a number using while loop in Python

 

Suggested for you

Operator in Python

Function in Python

For loop in Python

 

Python program to check whether a number is even or odd
Python program find factorial of a number using recursion
Exit mobile version