Reputation: 21
I'm planning to simplify my code without defining the function. Is it possible?
a = lambda x:1 if x>1 return x-1 else return x
output 0 = 0, 1=1 ,2=1 ,3=2
Upvotes: 0
Views: 230
Reputation: 439
a = lambda x:1 if x>1 return x-1 else return x
This is syntactically wrong. If you want to use if else, inline to make it work like a ternary operator in other languages. You will have to write:
# expression1 if condition else expression2
x-1 if x>1 else x
So it becomes:
a = lambda x: x-1 if x>1 else x
Remember lambda in python can only have a single line of code.
Upvotes: 2