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 :)
Lambda functions can only have one expression in their body. Regular functions can have multiple expressions and statements in their body.
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.
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.
To return multiple values pack them in a tuple. Then use multiple assignment to unpack the parts of the returned tuple.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With