Python ternary operator

Introduction

When using other programming languages ​​you may have been exposed have used the ternary operator, his basic syntax is "conditional expression expression 1:? 2 expression," that is a question mark in front of the judge when the conditions (conditional expressions when the formula), the determination result is true, the invocation expression 1, expression 2 is false calls.

In python, in fact, no such form of ternary operator, but python has his unique implementation, the syntax is "Expression 1 if the conditional expression else expression 2."

usage

For example, we now want to compare two numbers a, b, size, and then take the bigger number

Usually wording is:

if a >= b:
    max_value = a
else:
    max_value = b

When using the ternary operator:

c = a if a >= b else b

Guess you like

Origin www.cnblogs.com/mrdoghead/p/12180326.html