The basic ternary operator of Python

First, what is a ternary operator?

The ternary operator, also known as the ternary operator or the conditional operator, is implemented in python using the "if else" statement.
The ternary operator in python can be expressed as: exp1 if condition else exp2.
exp1 and exp2 are expressions, and condition is a judgment condition.

Second, commonly used ternary operators

1. Simple ternary operator

The ternary operator uses the if else statement to determine whether the condition is true, so as to determine the corresponding expression.

a = 20
b = 10
num = a if a > b else b
print(num)
# output: 20

a = 20
b = 30
num = a if a > b else b
print(num)
# output: 30

a = 25
b = 25
num = a if a > b else b
print(num)
# output: 25

a = 20
b = 10
num = a - b if a > b else a + b
print(num)
# output: 10

a = 10
b = 20
num = a - b if a > b else a + b
print(num)
# output: 30

c = 2
print('c为偶数') if c % 2 == 0  else ('c为奇数')
# output: c为偶数
c = 3
print('c为偶数') if c % 2 == 0  else ('c为奇数')
# output: c为奇数

2. Nested ternary operator

The nested ternary operator executes the if else statement sequentially, and multiple conditions can be set to select the corresponding expression.

a = 20
b = 10
c = 20
num = a if a > b else c if a + b > c else a + b
print(num)
# output: 20

a = 5
b = 20
c = 20
num = a if a > b else c if a + b > c else a + b
print(num)
# output: 20

a = 5
b = 10
c = 20
num = a if a > b else c if a + b > c else a + b
print(num)
# output: 15

For example, the above code first judges whether a>b is True, if it is True, then output a; if it is False, then continue to execute the next if else statement, that is, judge whether a+b>c is True, if it is True, then Output c; if False, output a+b.

Guess you like

Origin blog.csdn.net/m0_47026232/article/details/129230383