Introduction
The factorial of a number is the product of all positive integers less than or equal to that number. It is commonly denoted by n!
. Factorials are widely used in combinatorics, algebra, calculus, and many other fields of mathematics.
The factorial of a number n
is defined as:
n! = n × (n-1) × (n-2) × ... × 1
- For example,
5! = 5 × 4 × 3 × 2 × 1 = 120
- Special case:
0! = 1
(by definition).
In this program, we will calculate the factorial of a given number using Python programming language.
Objective
The objective of this program is to compute the factorial of a user-supplied number. This will demonstrate basic programming concepts such as loops, functions, and input/output in Python.
Python Code
# Python program to calculate the factorial of a number
# Function to calculate factorial
def factorial(n):
if n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result
# Input from the user
number = int(input("Enter a number to find its factorial: "))
# Checking for negative numbers
if number < 0:
print("Factorial is not defined for negative numbers.")
else:
# Calculating factorial and displaying the result
print(f"The factorial of {number} is {factorial(number)}")
Explanation of the Program
Let’s break down how this program works:
- Function Definition: The function
factorial(n)
calculates the factorial of a number. Ifn
is 0 or 1, it returns 1 (since 0! = 1 and 1! = 1). Otherwise, it uses a for loop to multiply the integers from 2 ton
together. - User Input: The program prompts the user to input a number using the
input()
function. This number is then converted to an integer usingint()
. - Negative Numbers: The program checks if the input number is negative. Since factorials are only defined for non-negative integers, it will display an error message if the user enters a negative number.
- Displaying the Result: If the input is valid, the program calls the
factorial()
function and prints the result in a user-friendly format.
How to Run the Program
- Install Python: Make sure Python is installed on your machine. You can download it from the official website: python.org.
- Create a Python File: Create a new file with a
.py
extension, such asfactorial_program.py
. - Write the Code: Copy and paste the Python code provided above into your Python file.
- Run the Program: Open a terminal or command prompt, navigate to the directory where your Python file is located, and run the program using the command:
python factorial_program.py
. - Enter a Number: When prompted, enter a number and the program will display its factorial.