Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use ternary operator for conditional assignment by python

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Editor to share with you how python uses the ternary operator for conditional assignment, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

Use the ternary operator for conditional assignment.

Ternary operators are shortcuts to if-else statements, also known as conditional operators.

[on_true] if [expression] else [on_false]

Here are some examples that you can use to make your code compact and concise.

The following statement has the same meaning, that is, "if y is 9, 10 is assigned to x, otherwise 20 is assigned to x." If necessary, we can extend the link to the operator.

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

Similarly, we can do the same thing with class objects.

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

In the above example, classA and classB are two classes, and one of the class constructors will be called.

Here is an example of not having it. Add the condition to evaluate the minimum number.

Def small (a, b, c): return an if a

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report