Question :
Write a program to find the factorial of a number using recursive function
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# The recursive function def factorial(n): if n == 1: return n else: return n*factorial(n-1) # take input from the user num = int(input("Enter a number: ")) # check is the number is negative if num < 0: print "Sorry, factorial does not exist for negative numbers" elif num == 0: print "The factorial of 0 is 1" else: print "The factorial of",num,"is",factorial(num) |
Explanation:
Factorial of a number is the product of all natural numbers till that number. It does not exist for negative numbers.
For example, the factorial of 4 would be 1*2*3*4=24
A recursive function is a function that calls on itself. In the above recursive function, the function calls on itself with n-1 as argument till n becomes 1 and 1 is returned. Each time the function is called, product the corresponding n and the factorial of n-1 is returned. Hence, factorial is found.
Output:
1.
1 2 |
Enter a number: -9 Sorry, factorial does not exist for negative numbers |
1 2 |
Enter a number: 1 The factorial of 1 is 1 |
1 2 |
Enter a number: 9 The factorial of 9 is 362880 |
Leave a Reply