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 :)
3 Answers 3
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.
Comments
You can use an anonymous dict inside your anonymous function to test for this, using the default value of dict.get to symbolize your final "else"
y = lambda sym: {False: 'X', True: 'Y'}.get(sym, ' ')
2 Comments
True and the value False, rather than testing for Truthyness or Falsyness. I'll editThis is one way where you can try multiple if else in lambda function
Example,
largest_num = lambda a,b,c : a if a>b and a>c else b if b>a and b>c else c if c>a and c>b else a
largest_num(3,8,14) will return 14
else?symbolcould be of any type?