【发布时间】:2022-12-27 21:48:36
【问题描述】:
I learned on the post How to write inline if statement for print? how to do inline if-else. Examples: Given assignment a=True, it expected the output 42 for statement print(42 if a else 24) and equivalent assignment x=42 on assignment x = (42 if a else 24).
Is there a way to use one further conditional statement i.e. 42 if a=='Hitchhicker' else if a=='Mountain-biker' 30 else 7?
【问题讨论】:
-
Did you try it?
-
42 if a=='Hitchhicker' else 30 if a=='Mountain-biker' else 7. But if there is more options it's better to initialize dictionaryd = {'Hitchhicker': 42, 'Mountain-biker': 30}and used.get(a, 7). -
It's not a statement but an expression, and all three parts of it can be any expression. You can go even further than
(a if b else c) if (d if e else f) else (g if h else i)if you want your coworkers to dislike you. -
Why do I receive "-1" votes? This is very annoying, community!
标签: python