TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Factorial Program in Python with Examples
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python ExamplesPython Tutorials

Factorial Program in Python with Examples

Last updated: Nov 05, 2023 12:06 am
By Harsh S.
Share
6 Min Read
Learn how to do factorial in python
SHARE

Let’s learn how to write a factorial program in Python with just a few lines of code. The factorial of a number is the product of all positive integers from 1 to that number.

Contents
1. Factorial Program in Python Using For LoopExampleSummary2. Factorial Program in Python Using RecursionExampleSummary3. Factorial Using Built-in Python FunctionExampleSummary4. Factorial Program with Error Handling5. Flowchart

In Python, we can write a simple and efficient algorithm to calculate factorials. Let’s explore how it can be done.

3 Ways to Find Factorial in Python

In this tutorial, we are covering the following methods.

  • The first method uses a for loop to write the logic.
  • In the second one, you will see recursion in action.
  • Thereafter, the example will utilize a built-in function.

And lastly, you’ll find a program with added error handling. A basic flowchart is also available at the end of the tutorial.

1. Factorial Program in Python Using For Loop

The program calculates factorial by multiplying numbers from 1 to the given number. It uses Python for loop to make the logic easier to understand.

Example

# Take user input to calculate factorial
num = int(input("Enter a number: "))
factorial = 1

# Check if the input is negative, positive or zero
if num < 0:
    print("Factorial of negative value is not defined")
elif num == 0:
     print("Factorial of  0 is ‘1’")
else:
    for i in range(1, num+1):
        factorial *= i
    print("The factorial of", num, "is", factorial)

Summary

It was a simple factorial program in Python using the for loop.

1) The code first verifies whether the user input is positive, negative, or zero.

2) If it is positive the loop starts from 1 and goes up to num+1. The range() function excludes the upper limit. The program multiples the factorial variable by each number in the loop.

In short, the code prompts the user to enter a number. After that, it calculates the factorial using a loop and then displays the result to the user.

2. Factorial Program in Python Using Recursion

This program calculates factorial using recursion, calling itself to multiply numbers. This approach simplifies the process in Python, making it easier to understand and implement.

Example

# Recursive factorial function
def factorial(n):
    if n == 0:
        return 1
    else:
        # Recursive call to the factorial function
        return n * factorial(n-1)

# Asking the user to supply input
num = int(input("Enter a value: "))

# Call the Factorial function
result = factorial(num)
print("The factorial of", num, "is", result)

Summary

The above program demonstrates factorial calculation in Python using recursion.

1) The code first defines a factorial function that uses recursion. It first prompts the user to enter a value.

2) The program then calls the factorial function with the given input.

3) The factorial function calls itself recursively, each time decreasing the value of ‘num’ by 1.

4) By the time, the value of ‘num’ becomes 0, the factorial of the number is calculated and saved in the result.

3. Factorial Using Built-in Python Function

This program calls a built-in Python function, i.e., factorial(). It is a much simpler approach than the previous two.

However, it requires the use of an external module.

Example

import math

n = int(input ("Input the number: "))
result = math.factorial(n)

print("The factorial of", n, "is", result)

Summary

The above Python factorial program follows below simple steps.

1) In the first line, we import the math module. It allows us to do various mathematical operations.

2) We then define the variable “n” for which we want to calculate the factorial.

3) Next, we call the math.factorial() function with num as the argument. And then stores the output in the variable result.

4) Finally, we will print the result of the Python example to the console.

Please note that the factorial() function works only for non-negative integers. It will raise a ValueError exception for any negative value or a non-integer input.

4. Factorial Program with Error Handling

Here is one more example of factorial in Python. It also does error handling.

def factorial(n):
    if n < 0:
        raise ValueError("factorial is not defined for negative values")
    elif n == 0:
        return 1
    else:
        return n * factorial(n-1)

# Example usage
try:
    fact = int(input("Enter a number: "))
    print("The factorial of", fact, "is", factorial(fact))
except ValueError as e:
    print("Error:", e)

5. Flowchart

As we are now at the end of this tutorial, review this basic flowchart model. It covers the steps of a general factorial program in Python.

Visualize the steps of a factorial program in Python using for loop

Quick Wrap Up

To sum up, the factorial program in Python is a helpful exercise for beginner programmers to hone their programming skills. It even makes them recall basic math concepts and think about their logic.

By learning and using this program, you can improve your problem-solving skills and explore more possibilities in Python programming.

Happy Coding!

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article 4 ways to find all possible string permutation in Python Find All Possible Permutation of a String in Python
Next Article Python dataclasses tutorial for beginners Get Started with DataClasses in Python

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x