0

How to make a code for factorial of a input

5th Jul 2021, 5:25 AM
Mrunmay dawkhar
Mrunmay dawkhar - avatar
10 Answers
+ 5
Mrunmay dawkhar , the presented codes and solutions looks nice and are performing well. but recursion and lambda may not be what a beginner would want to try. i am also missing some explanations to these codes. i wonder why nobody is showing a for loop, that can do this task also. it may be not look as cool as the other solutions, but here is the try: number = int(input()) # (1) res = 1 # (2) for num in range(1,number +1): #(3) res = res * num # (4) print(res) (1) input that is given has to be converted to int, as input returns a string by default (2) a variable for the result is declared and initialized with 1. if 0 would be taken to initialize, the result will be 0 as a multiplication is performed (3) for loop uses a range, starting with 1 and running up to input number. as the last number in range is excluded, we need to add +1 (4) the short version of this is: res *= num and can olso be used. happy coding and good success!
5th Jul 2021, 9:26 AM
Lothar
Lothar - avatar
+ 3
Calvin Thomas As much as I dislike how limited Python lambdas are, this was a super clean solution. The walrus operator was a nice touch for making this recursively possible using the lambda. Passing the input as an argument to the immediately self called lambda was brilliant. Well done 👌
5th Jul 2021, 8:12 AM
David Carroll
David Carroll - avatar
+ 1
def fact(n): if(n == 1 or n == 0): return 1 return n*fact(n-1) n = int(input("Enter a number = ")) print("Factorial of ",n," = ",fact(n))
5th Jul 2021, 6:21 AM
Sumit Kumar
Sumit Kumar - avatar
+ 1
Mrunmay dawkhar Here's a one-liner: print((a:=lambda x: x * a(x-1) if x else 1)(int(input()))) # Hope this helps
5th Jul 2021, 7:54 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
David Carroll Thank you!
5th Jul 2021, 8:18 AM
Calvin Thomas
Calvin Thomas - avatar
+ 1
Mrunmay dawkhar I would like to share a code that was shown to me by Atul [Inactive] . A simple solution, but I agree with Lothar , if you create your own simple code, you gain an understanding of why it works. https://code.sololearn.com/cL9gw4Q4xAQZ/?ref=app
5th Jul 2021, 9:46 AM
Rik Wittkopp
Rik Wittkopp - avatar
0
Make a recursion of function which return "num * factorial (num-1)" Until num is 1 .& set stop condition as "if num ==1: return 1 " 👍
5th Jul 2021, 5:51 AM
Yash Wable 🇼🇳
Yash Wable 🇼🇳 - avatar
0
Thanks 👍
5th Jul 2021, 6:02 AM
Mrunmay dawkhar
Mrunmay dawkhar - avatar
0
Python is first language i am learning so this seems too complex for me
5th Jul 2021, 8:15 AM
Mrunmay dawkhar
Mrunmay dawkhar - avatar
5th Jul 2021, 12:16 PM
Sumit Kumar
Sumit Kumar - avatar