Skip to main content

Write a python program to Calculate Factorial of given Number

Description

The provided Python code defines a recursive function named 'recursion' for calculating the factorial of a given positive integer 'n.' It solicits user input for 'n,' computes the factorial using recursion, and displays the result. The code handles cases where 'n' is less than 1 by indicating that factorial calculation is not possible for non-positive integers. It successfully calculates and communicates the factorial value for positive integers.

Code

program9b.py
def recursion(n):
if(n<1):
print("Factorial not possible")
elif(n>1):
return n*recursion(n-1)
else:
return 1
n=int(input("enter number:"))
print("Factorial of given number is",recursion(n))

Explanation of above code

  • Function Definition: The code introduces a recursive Python function named 'recursion' tailored for factorial calculation. It leverages recursion to efficiently compute the factorial of an input number 'n.'
  • Recursive Factorial Calculation: Within the 'recursion' function, a series of recursive cases unfolds:
  • When 'n' is less than 1, the code responds by signaling 'Factorial not possible,' recognizing the absence of a factorial definition for non-positive integers.
  • For 'n' greater than 1, the function recursively calculates the factorial by returning 'n' multiplied by 'recursion(n-1).' This iterative process breaks down the factorial problem into smaller, manageable subproblems.
  • When 'n' assumes the value of 1, the function promptly returns 1, acknowledging the well-defined factorial of 1.
  • User Input: The code actively engages with the user by soliciting numeric input. This input is acquired and stored within the variable 'n' for subsequent processing.
  • Factorial Calculation: With 'n' in hand, the code invokes the 'recursion' function, submitting 'n' as the argument. The result of this recursive computation is captured in a designated variable.
  • Printing the Result: The code culminates its journey by elegantly presenting the result to the user. It articulates the calculated factorial value prefaced by the informative message, 'Factorial of the given number is.'
  • Recursive Factorial Calculation: Factorial, symbolized as 'n!,' denotes the product of all positive integers from 1 to 'n.' Recursive factorial computation employs the paradigm of recursion to break down the complex factorial problem into smaller, comprehensible subproblems.
  • Output: Upon receiving a positive integer from the user, the code diligently computes and showcases the factorial value. However, when a non-positive integer (less than 1) is offered, it gracefully responds with 'Factorial not possible,' acknowledging the mathematical constraints associated with factorial definitions for non-positive integers. Thus, the code exercises mathematical awareness and conveys results with precision.

Learn more

Reference