Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
filter() in python
Next article icon

factorial() in Python

Last Updated : 09 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Not many people know, but python offers a direct function that can compute the factorial of a number without writing the whole code for computing factorial.

Naive method to compute factorial

Python
# Python code to demonstrate naive method # to compute factorial n = 23 fact = 1  for i in range(1, n+1):     fact = fact * i  print("The factorial of 23 is : ", end="") print(fact) 

Output
The factorial of 23 is : 25852016738884976640000 

Time Complexity: O(n)
Auxiliary Space: O(1)

Using math.factorial()

This method is defined in “math” module of python. Because it has C type internal implementation, it is fast.

math.factorial(x)
Parameters :
x : The number whose factorial has to be computed.
Return value :
Returns the factorial of desired number.
Exceptions :
Raises Value error if number is negative or non-integral.
Python
# Python code to demonstrate math.factorial() import math  print("The factorial of 23 is : ", end="") print(math.factorial(23)) 

Output
The factorial of 23 is : 25852016738884976640000 

Time Complexity: O(n)
Auxiliary Space: O(1)

Exceptions in math.factorial()

  • If given number is Negative : 
Python
# Python code to demonstrate math.factorial() # Exceptions ( negative number )  import math  print("The factorial of -5 is : ", end="")  # raises exception print(math.factorial(-5)) 

Output:

Traceback (most recent call last):
File "/home/f29a45b132fac802d76b5817dfaeb137.py", line 9, in
print (math.factorial(-5))
ValueError: factorial() not defined for negative values
  • If given number is Non – Integral Value : 
Python
# Python code to demonstrate math.factorial() # Exceptions ( Non-Integral number )  import math  print("The factorial of 5.6 is : ", end="")  # raises exception print(math.factorial(5.6)) 

Output:

Traceback (most recent call last):
File "/home/3987966b8ca9cbde2904ad47dfdec124.py", line 9, in
print (math.factorial(5.6))
ValueError: factorial() only accepts integral values



Next Article
filter() in python
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Python
  • Python-Library
Practice Tags :
  • python

Similar Reads

  • Python | math.factorial() function
    In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.factorial() function returns the factorial of desired number. Syntax: math.factorial(x) Parameter: x: This is a numeric expression. Returns: factorial of desired number. Time
    2 min read
  • float() in Python
    Python float() function is used to return a floating-point number from a number or a string representation of a numeric value. Example: Here is a simple example of the Python float() function which takes an integer as the parameter and returns its float value. C/C++ Code # convert integer value to f
    3 min read
  • Python int() Function
    The Python int() function converts a given object to an integer or converts a decimal (floating-point) number to its integer part by truncating the fractional part. Example: In this example, we passed a string as an argument to the int() function and printed it. [GFGTABS] Python age = "21"
    4 min read
  • filter() in python
    The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let's see a simple example of filter() function in python: Example Usage of filter()[GFGTABS] Python # Function to check if a number is even def even(n): return n % 2
    3 min read
  • eval in Python
    Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression (code) within the program. Python eval() Function SyntaxSyntax: eval(expression, globals=None, locals=None) Parameters: expression: String is parsed and evaluated as a Python expres
    6 min read
  • Python | sympy.factorial() method
    With the help of sympy.factorial(), we can find the factorial of any number by using sympy.factorial() method. Syntax : sympy.factorial() Return : Return factorial of a number. Example #1 : In this example we can see that by using sympy.factorial(), we are able to find the factorial of number that i
    1 min read
  • Python input() Function
    Python input() function is used to take user input. By default, it returns the user input in form of a string. input() Function Syntax:  input(prompt)prompt [optional]: any string value to display as input message Ex: input("What is your name? ") Returns: Return a string value as input by the user.
    4 min read
  • Python | sympy.factorial2() method
    With the help of sympy.factorial2() method, we can find the Double factorial. Double factorial of a number is given by - [Tex] n!! = \begin{cases} 1 & n = 0 \\ n(n-2)(n-4) \cdots 1 & n\ \text{positive odd} \\ n(n-2)(n-4) \cdots 2 & n\ \text{positive even} \\ (n+2)!!/(n+2) & n\ \text{
    1 min read
  • gcd() in Python
    The Highest Common Factor (HCF), also called gcd, can be computed in python using a single function offered by math module and hence can make tasks easier in many situations. Naive Methods to compute gcdWay 1: Using Recursion C/C++ Code # Python code to demonstrate naive # method to compute gcd ( re
    2 min read
  • Python Functions
    Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences