Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple if statements in a lambda function

Tags:

I am trying to use 3 if statements within a python lambda function. Here is my code:

y=lambda symbol: 'X' if symbol==True 'O' if symbol==False else ' '

I Have been able to get two if statements to work just fine e.g.

x=lambda cake: "Yum" if cake=="chocolate" else "Yuck"

Essentially, I want a lambda function to use if statements to return 'X' if the symbol is True, 'O' if it is false, and ' ' otherwise. I'm not even sure if this is even possible, but I haven't been able to find any information on the internet, so I would really appreciate any help :)

like image 548
Rational Function Avatar asked Oct 30 '15 15:10

Rational Function


People also ask

Can lambda function have multiple statements?

Lambda functions can only have one expression in their body. Regular functions can have multiple expressions and statements in their body.

Can you put an if statement in a lambda?

Using if-else in lambda function The lambda function will return a value for every validated input. Here, if block will be returned when the condition is true, and else block will be returned when the condition is false.

Can we use if statement in Lambda Python?

value_1 is returned if condition is true, else value_2 is returned. You can have an expression that evaluates to a value in the place of value_1 or value_2. You can have nested if else in lambda function. Following is the syntax of Python Lambda Function with if else inside another if else, meaning nested if else.

Can Lambda return multiple values?

To return multiple values pack them in a tuple. Then use multiple assignment to unpack the parts of the returned tuple.


1 Answers

You are missing an else before 'O'. This works:

y = lambda symbol: 'X' if symbol==True else 'O' if symbol==False else ' '

However, I think you should stick to Adam Smith's approach. I find that easier to read.

like image 192
Cristian Lupascu Avatar answered Oct 07 '22 01:10

Cristian Lupascu