-2

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?

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • 2
    Did you try it? – Scott Hunter Dec 27 '22 at 13:48
  • 1
    `42 if a=='Hitchhicker' else 30 if a=='Mountain-biker' else 7`. But if there is more options it's better to initialize dictionary `d = {'Hitchhicker': 42, 'Mountain-biker': 30}` and use `d.get(a, 7)`. – Olvin Roght Dec 27 '22 at 13:48
  • 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. – molbdnilo Dec 27 '22 at 13:51
  • 1
    Why do I receive "-1" votes? This is very annoying, community! – Bruno Peixoto Dec 27 '22 at 13:52
  • 1
    @molbdnilo I challenge you to answer "What should I do to make my coworkers like me?". I never found a great answer to this question. – Bruno Peixoto Dec 27 '22 at 13:57

2 Answers2

0

You can do this:

42 if a=='Hitchhicker' else 30 if a=='Mountain-biker' else 7
Aymen
  • 841
  • 1
  • 12
  • 21
0

You can also do this way:

((7,42)[a=='Hitchhicker'],30)[a=='Mountain-biker']
Arifa Chan
  • 947
  • 2
  • 6
  • 23