Get the App
SLTechnology News&Howtos  ›  Development  › 

How python uses ternary operators to perform conditional assignments

Shulou Source: shulou.com Published: 2022-06-01 04:52:10 09月16日 Update

This article mainly introduces how python uses ternary operators to carry out conditional assignment. It has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.

Conditional assignment using ternary operators

The ternary operator is a shortcut to if-else statements, i.e. conditional operators:

[return value if expression is true] if [expression] else [return value if expression is false]

Here are a few examples you can use to make your code compact and concise. The following statement says,"If y is 9, assign x 10, otherwise assign x 20." We can also extend the chain of operations if necessary.

x = 10 if (y == 9) else 20

Similarly, we can do this with classes:

x = (classA if y == 1 else classB)(param1, param2)

In the example above classA and classB are two classes, one of which has a constructor called.

Here is another example of multiple conditional expressions chained together to calculate a minimum:

def small(a,b,c):returnaifa

Tags: Operators conditions ternary articles expressions examples statements face minimum concise compact two that is code value interest function simultaneously multiple way Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Technology Shulou Tech Info Xiaomi Microsoft