Factorial Calculation in Python

PythonPythonBeginner
Practice Now

Introduction

In this project, you will learn how to calculate the factorial of a non-negative integer. The factorial of a positive integer is the product of all positive integers less than or equal to it, and the factorial of 0 is 1.

👀 Preview

$ python factorial.py
2! = 1 * 2 = 2
8! = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 = 40320

🎯 Tasks

In this project, you will learn:

  • How to create a factorial.py file in the ~/project directory
  • How to implement the factorial function to calculate the factorial of a non-negative integer
  • How to handle negative inputs by raising a ValueError and display a prompt saying "Please enter a non-negative integer"

🏆 Achievements

After completing this project, you will be able to:

  • Understand the concept of factorial and how to calculate it
  • Write a Python function to calculate the factorial of a non-negative integer
  • Handle input errors and display appropriate error messages
  • Apply your knowledge of Python programming to solve a real-world problem

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/numeric_types("`Numeric Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("`Raising Exceptions`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/variables_data_types -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/numeric_types -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/strings -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/type_conversion -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/conditional_statements -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/for_loops -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/lists -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/tuples -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/sets -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/function_definition -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/raising_exceptions -.-> lab-302699{{"`Factorial Calculation in Python`"}} python/build_in_functions -.-> lab-302699{{"`Factorial Calculation in Python`"}} end

Create the factorial.py File

In this step, you will create the factorial.py file in the ~/project directory. Follow the steps below to complete this step:

  1. Create a new file and save it as factorial.py in the ~/project directory.
cd ~/project
touch factorial.py
  1. In the factorial.py file, add the following code:
def factorial(n):
    """
    Calculate the factorial of a non-negative integer.

    Args:
        n (int): The non-negative integer for which to calculate the factorial.

    Returns:
        str: The factorial of the input integer in the format "{n}! = {factors_str} = {result}".

    Raises:
        ValueError: If the input integer is negative.
    """
    ## Add your code here

This is the starting point for the factorial function that you will implement in the next step.

Implement the factorial Function

In this step, you will implement the factorial function in the factorial.py file. Follow the steps below to complete this step:

  1. In the factorial.py file, replace the ## Add your code here comment with the following code:
def factorial(n):
    """
    Calculate the factorial of a non-negative integer.

    Args:
        n (int): The non-negative integer for which to calculate the factorial.

    Returns:
        str: The factorial of the input integer in the format "{n}! = {factors_str} = {result}".

    Raises:
        ValueError: If the input integer is negative.
    """
    if n < 0:
        raise ValueError("Please enter a non-negative integer.")
    elif n == 0:
        return "0! = 1"
    else:
        result = 1
        factors = []
        for i in range(1, n + 1):
            result *= i
            factors.append(str(i))
        factors_str = " * ".join(factors)
        return f"{n}! = {factors_str} = {result}"

## Partial example printout:
print(factorial(2))
print(factorial(8))

This code implements the functionality of calculating the factorial of a non-negative integer. It handles the case of a negative input by raising a ValueError, and the case of 0 by returning "0! = 1". For all other non-negative integers, it calculates the factorial by multiplying all the numbers from 1 to the input number, and returns the result in the desired format.

  1. Save the factorial.py file.

Your factorial.py file is now complete, and you can use the factorial function to calculate the factorial of any non-negative integer.

  1. To test your implementation, run the following command in your terminal:
$ python factorial.py
2! = 1 * 2 = 2
8! = 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 = 40320

Summary

Congratulations! You have completed this project. You can practice more labs in LabEx to improve your skills.

Other Python Tutorials you may like