Ternary operation in python

Ternary operation

Ternary operation, also known as ternary operation, is a shorthand for simple conditional statements, such as:

Simple conditional statement:

if condition is satisfied:

    val = 1

else:

    val = 2

Change it to a ternary operation:

val = 1 if condition is true else 2

1 >>> a = 2
2 >>> b = 5
3 >>> a = b if a >b else a
4 >>> a
5 2
6 >>> a = b if a >b else 4
7 >>> a
8 4

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325113147&siteId=291194637