find factorial by lambda function in python by R4R Team

-Factorial of any number is multiplication of all 1,2,3,4,.... upto that number.

Example -

5!=1*2*3*4*5

4!=1*2*3*4

Lambda function-

-In Python, anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.

Syntax-

lambda argument:expression


program-

#lambda function which find factorial
fact=lambda x: 1 if x==0 else x*fact(x-1)

print("Enter number to find factorial")
n=int(input())
print("Factorial of ",n,"is",fact(n))
print()

print("Factorial of 6 is",fact(6))
print("Factorial of 7 is",fact(7))
print("Factorial of 8 is",fact(8))
print("Factorial of 4 is",fact(4))


output-

Enter number to find factorial
5
Factorial of 5 is 120
Factorial of 6 is 720
Factorial of 7 is 5040
Factorial of 8 is 40320
Factorial of 4 is 24


-In this program, we make a lambda function named as fact() which are fact=lambda x: 1 if x==0 else x*fact(x-1), here we pass a argument i.e number and it check by condition
1 if x==0 else x*fact(x-1) that means it return 1 when x become 0 and otherwise it called itself with lesser value.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!