Sure! Let's create a simple Python module that provides a function to calculate the factorial of a number. The factorial of a non-negative integer \( n \) is the product of all positive integers less than or equal to \( n \). It's commonly used in mathematics, particularly in combinatorics.
Here's how we can implement this:
Step 1: Create the Module
You can create a new file named factorial.py
for your module. Here is the code for the module:
# factorial.py
def factorial(n):
"""
Returns the factorial of a non-negative integer n.
Parameters:
n (int): A non-negative integer
Returns:
int: The factorial of n
"""
if n < 0:
raise ValueError("Factorial is not defined for negative numbers.")
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
Step 2: Using the Module
You can now use this module in another Python script. Create a new file named main.py
and include the following code:
# main.py
from factorial import factorial
def main():
number = int(input("Enter a non-negative integer: "))
try:
result = factorial(number)
print(f"The factorial of {number} is {result}")
except ValueError as e:
print(e)
if __name__ == "__main__":
main()
Explanation
-
factorial.py:
- Contains a single function
factorial
which computes the factorial. - The function raises a
ValueError
if a negative integer is passed. - The factorial is calculated iteratively.
- Contains a single function
-
main.py:
- Imports the
factorial
function from thefactorial
module. - Asks the user for a non-negative integer, computes its factorial, and prints the result.
- Catches any potential exceptions (like entering a negative number) and prints the error message.
- Imports the
Running the Code
To run the program, make sure both factorial.py
and main.py
are in the same directory. Run the main.py
script, and it will prompt you to enter a non-negative integer, then it will display the factorial.
$ python main.py
Enter a non-negative integer: 5
The factorial of 5 is 120
That's it! You now have a simple Python module to calculate factorials.