Python ternary operations

Source: Internet
Author: User

Ternary operators

Ternary operators are often referred to as conditional expressions in Python, which are based on the condition of True (TRUE)/False (false), and have ternary operations above Python 2.4.

Here is a pseudo-code and an example:

Pseudo code:

#如果条件为真,返回真 否则返回假condition_is_true if condition else condition_is_false

Example:

is_fat = Truestate = "fat" if is_fat else "not fat注意这个

It allows for quick judgment with a simple line, rather than using complex multiline if statements. This is useful most of the time and makes the code easy to maintain.

Another obscure usage is rare, it uses tuples, please continue to see:

Pseudo code:

#(返回假,返回真)[真或假](if_test_is_false, if_test_is_true)[test]

Example:

fat = Truefitness = ("skinny", "fat")[fat]print("Ali is", fitness)#输出: Ali is fat

This works because in Python, true equals 1, and false equals 0, which is equivalent to selecting data using 0 and one in the tuple.

The above example is not widely used, and Python players generally dislike that because there is no Python flavor (pythonic). Such usage can easily confuse real data with True/false.

Another reason for not using tuple conditional expressions is because the two conditions are executed in the tuple, and if-else the conditional expressions do not.

For example:

condition = Trueprint(2 if condition else 1 / 0)#输出: 2print((1 / 0, 2)[condition])#输出ZeroDivisionError异常

This is because the data is first built in the tuple and then indexed to the data with true (1)/false (0). if-elseconditional expressions follow a normal if-else logical tree, so it is best to avoid using tuple conditional expressions if the conditions in the logic are abnormal, or if they are recalculated (longer).

Python ternary operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.