python if Ternary Expression Example Usage Detailed Explanation

  • 2021-11-02 01:36:28
  • OfStack

1. Description

Use 1 line of code to quickly judge and replace complex multi-line if statements, so that the code can be easily maintained.

The reading style of if3 meta-expression is a bit out of line with reading habits. Read from the if condition in the middle of the sentence. If the condition is met, get the value x on the left. If the condition is not met, get the value x below else.

2. Examples


result = x if x > 0 else -x
>>> x = -15
>>> x if x > 0 else -x
15

Extension of knowledge points:


public class java {
 public static void main(String[] args){
 int x = 100;
 int y = 101;
 int MAX = (x > y)? x: y;
 System.out.println("MAX:" + MAX);
 }
}

The above example can well illustrate the format of other languages:

Conditions of judgment? The result when the condition is true: the result when the condition is false

Although there are 3 yuan expressions in Python, the formats are different. Let's look at a simple example in Python first


>>> x = 4
>>> y = 99 if x > 3 else 999
>>> y
99

As can be seen from the above example of Python, the 3 yuan expression format of Python is as follows:

The result of if when the condition is true the result of else when the condition is false


Related articles: