Yes, it was added in version 2.5. The syntax is:
a if test else b
First test
is evaluated, then either a
or b
is returned based on the Boolean value of test
;
if test
evaluates to True a
is returned, else b
is returned.
For example:
>>>'true'ifTrueelse'false''true'>>>'true'ifFalseelse'false''false'
Keep in mind that it's frowned upon by some Pythonistas for:
If you're having trouble remembering the order (as many seem to do), then remember that if you read it out loud, you (almost) say what you mean x = 4 if b > 8 else 9
is read out loud as x will be 4 if b is greater than 8 otherwise 9
.