Home » Python programs

Python | Find factorial of a given number (2 different ways)

Here, we are going to implement logic to find factorial of given number in Python, there are two methods that we are going to use 1) using loop and 2) using recursion method.
Submitted by IncludeHelp, on August 09, 2018

Given a number and we have to find its factorial in Python.


    Num = 4

    Factorial of 4 is: 24

1) Method 1: Using loop

# Code to find factorial on num

# number
num = 4

# 'fact' - variable to store factorial 
fact =1 

# run loop from 1 to num
# multiply the numbers from 1 to num
# and, assign it to fact variable 

for i in range (1,num+1) :
	fact = fact*i 

# print the factorial
print "Factorial of {0} is: {1} ".format (num, fact)


    Factorial of 4 is: 24 

2) Method 2: by creating a function using recursion method

To find the factorial, fact() function is written in the program. This function will take number (num) as an argument and return the factorial of the number.

# function to calculate the factorial 
def fact (n):
	if n == 0:
		return 1 
	return n * fact (n - 1)

# Main code 
num = 4

# Factorial
print "Factorial of {0} is: {1} ".format (num, fact(num))


    Factorial of 4 is: 24 

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Quick links
Latest articles, Internship, Members
Coding problems, Algorithms, Discrete Mathematics, Big data
C, C++, C++ STL, Java, Data Structure, C#.Net, Android, Kotlin, SQL
PHP, Python, JavaScript, CSS, Ajax, Node.js, Web prog.
C, C++, DS, Java, C#, Python
C, C++, Java, DBMS
C, Embedded C, Java, SEO, HR
CS Subjects
CS Basics O.S. Networks DBMS Embedded Systems Cloud Computing Machine learning CS Organizations Linux DOS
Articles, Puzzles, News/Updates

Recommended posts
C Tips & Tricks, C++ Tips & Tricks
Introduction to Linux (Its modes, Safety, Most popular Applications)
Linux Best Distros of 2018
C programming optimization techniques
Differences b/w C & Embedded C?
Embedded C Interview Q. & A.
C programming tips for Embedded Development
Basic rules of writing a C program
Important points (rules) to remember while writing C/C++ program
Top 5 Websites for solving programming challenges

Computer G.K. (MCQ)
Most viewed pages...

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.