top of page
learn_data_science.jpg

Data Scientist Program

 

Free Online Data Science Training for Complete Beginners.
 


No prior coding knowledge required!

Python Program to Find the Factorial of an Integer

Updated: Sep 15, 2021

In this article, we will find the factorial of a number with python.

 

The factorial of a number is the product of all the integers from 1 to that number.

For example, the factorial of 6 is 1*2*3*4*5*6* = 720.

Factorial is not defined for negative numbers, and the factorial of zero is one, 0! = 1.


 

We will implement two methods to solve the factorial of a number.


Method 1:

Step 1:

First, we will define the factorial function which will take an interger argument n.

def factorial(n):

Step 2:

Initialising the factorial to 1

factorial = 1

Step 3:

If n is equal to 0 the factorial will be 1 by default.

if n == 0: return 1

Step 4:

Else, we implement a for loop to iterate through intergers ranging from 1 to n to return their product.

else:
    for i in range(1,n+1):
        factorial *= i
return factorial

Let's apply this code !

factorial(8)
40320
 

Method 2:

Step 1: Recursive function

We will implement a function that recursively calls itself by decreasing the number..

First, we will define the factorial_rec function which will take an interger argument n.

def factorial_rec(n):

Step 2:

Base condition n=0 :

if n == 0:
    return 1

Step 3:

Recursion:

return factorial_rec(n-1)

Let's apply this code !

factorial_rec(5)
120
factorial_rec(0)
1
 
 
 
 

3 Comments


Data Insight
Data Insight
Sep 15, 2021

Nice! You should replace all code images with code snippets.

Like
Data Insight
Data Insight
Sep 15, 2021
Replying to

The same way you inserted def factorial(n):. Just use the code snippets instead of the images.

Like

COURSES, PROGRAMS & CERTIFICATIONS

 

Advanced Business Analytics Specialization

Applied Data Science with Python (University of Michigan)

Data Analyst Professional Certificate (IBM)

Data Science Professional Certificate (IBM)

Data Science Specialization (John Hopkins University)

Data Science with Python Certification Training 

Data Scientist Career Path

Data Scientist Nano Degree Program

Data Scientist Program

Deep Learning Specialization

Machine Learning Course (Andrew Ng @ Stanford)

Machine Learning, Data Science and Deep Learning

Machine Learning Specialization (University of Washington)

Master Python for Data Science

Mathematics for Machine Learning (Imperial College London)

Programming with Python

Python for Everybody Specialization (University of Michigan)

Python Machine Learning Certification Training

Reinforcement Learning Specialization (University of Alberta)

Join our mailing list

Data Insight participates in affiliate programs and may sometimes get a commission through purchases made through our links without any additional cost to our visitors.

bottom of page