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

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
âœĻ Check Solution and Practice

Summary

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

Other Python Tutorials you may like