
Zekka N. answered 03/13/19
Java and Python Tutor, Also Knows Obscure Programming Languages
Hello!
Python does have a ternary conditional operator. Consider the case where you would normally write this:
You can always instead write this:
true_body will only be evaluated if condition is true; likewise, false_body will only be evaluated if condition is false. These are the same rules C uses for its equivalent language construct:
Many Python programmers use a dictionary literal for more complicated versions of this situation -- such as this one where the programmer has to distinguish between three options and a default value:
However, be cautioned that in the dictionary literal solution, Python evaluates every item. In other words: