how.wtf

Ternary operator in Python

· Thomas Taylor

The ternary operator is an in-line if/else statement that many languages support natively; however, Python does not have a specific operator. Instead, it uses conditional expression resolution which was added in Python 2.5.

In-line if/else statement

An in-line if/else statement in Python looks like the following:

1'true' if True else 'false'

Output:

1'true'

Breaking down the syntax,

1true_value if condition else false_value

Return the value of the “idle” stage for a blue/green deployment.

1def get_active_stage():
2    # logic to get the active stage
3    return "blue"
4
5idle_stage = "green" if get_active_stage() == "blue" else "blue"
6print(stage)

Output:

1green

#python  

Reply to this post by email ↪