Basic Python code for factorial calculation
Calculating Factorial of a Number Using Recursion in Python
def calcfact(n):
"""Recursive function to calculate factorial."""
if n == 0:
return 1 # Base case: factorial of 0 is 1
else:
return n * calcfact(n - 1) # Recursive case
def main():
number = int(input("Enter a non-negative integer: "))
if number < 0:
print("Please enter a non-negative number.")
else:
fact = calcfact(number)
print(f"The factorial of {number} is {fact}")
if __name__ == "__main__":
main()
Introduction
In this post, we will explore how to calculate the factorial of a non-negative integer using a recursive function in Python. The factorial of a number (denoted as ) is the product of all positive integers up to .
Step 1: Define the Recursive Function
We start by defining a function calcfact(n)
that will calculate the factorial recursively.
def calcfact(n):
if n == 0:
return 1
else:
return n * calcfact(n - 1)
Explanation:
- Base Case: The first line checks if is 0. If true, it returns 1. This is because the factorial of 0 is defined as 1.
- Recursive Case: If is greater than 0, the function returns multiplied by the factorial of . This continues until it reaches the base case.
Step 2: Create the Main Function
Next, we create the main()
function that will handle user input and output.
def main():
number = int(input("Enter the non-negative number: "))
if number < 0:
print("Please enter a non-negative number")
else:
fact = calcfact(number)
print(f"The factorial of {number} is {fact}")
Explanation:
- User Input: The function prompts the user to enter a non-negative integer and converts the input to an integer.
- Input Validation: If the entered number is negative, it prints a message asking for a non-negative number.
- Factorial Calculation: If the input is valid, it calls the
calcfact()
function to compute the factorial and stores the result in the variablefact
. - Output: Finally, it prints the result using an f-string for formatting.
Step 3: Execute the Program
The last part of the code ensures that the main()
function is called when the script is executed directly.
if __name__ == "__main__":
main()
Explanation:
- This line checks if the script is being run directly (not imported as a module) and calls the
main()
function. This is a common practice in Python to allow or prevent parts of code from being run when the module is imported.
Conclusion
This simple Python program demonstrates how to calculate the factorial of a non-negative integer using recursion. Recursive functions are a powerful tool in programming, allowing us to solve problems by breaking them down into smaller, more manageable sub-problems.
Example Output
Enter the non-negative number: 5
The factorial of 5 is 120
Comments
Post a Comment