FINDING FACTORIAL OF A NUMBER IN PYTHON
How to find factorial of a number using python.
To find the factorial of a number in python we have two main methods as follows :
1. Using for loop in python
2. Using recursion
1. Using for loop in python
By using python for loop we can find the factorial of a number as follows :
#choosing a number
n = 5
#setting a base value of factorial
factorial = 1
#checking conditions
if n < 0:
print ("factorial does not exist")
elif n == 0:
print ("factorial of 0 is 1")
else :
for i in range (1,n+1):
#incrementing the value of factorial
factorial = factorial*i
print (factorial)
2. Using recursion
The second way of finding the factorial of a number using recursion method is as follows:
#defining function
def factorial(n):
if n == 0:
return 1
# recursion
return n*factorial(n-1)
answer = factorial(5)
#print factorial
print(answer)
Amazing... it's really helpful... thanku
ReplyDelete