Factorial Program Using Recursion in This Program, The Factorial Function Takes An Integer N As Input And Calculates Its Factorial Using Recursion.
The Base Case Is When N Is 0, In Which Case The Function Returns 1 (Since The Factorial Of 0 Is Defined As 1). For Any Other Value Of N, The Function Calls Itself With N-1 As The Argument And Multiplies The Result By N. This Recursive Call Continues Until N Becomes 0.
Finally, We Test The Factorial Function By Taking A User Input And Calculating The Factorial Of That Number. The Result Is Then Displayed On The Console.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
# Test the factorial function
num = int(input("Enter a non-negative integer: "))
result = factorial(num)
print("The factorial of", num, "is", result)

No comments:
Post a Comment