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.pyfile in the~/projectdirectory - How to implement the
factorialfunction to calculate the factorial of a non-negative integer - How to handle negative inputs by raising a
ValueErrorand 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:
- Create a new file and save it as
factorial.pyin the~/projectdirectory.
cd ~/project
touch factorial.py
- In the
factorial.pyfile, 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:
- In the
factorial.pyfile, replace the## Add your code herecomment 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.
- Save the
factorial.pyfile.
Your factorial.py file is now complete, and you can use the factorial function to calculate the factorial of any non-negative integer.
- 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.



