How to use the ternary operator in Python
This article mainly introduces how to use the ternary operator in Python. It is very detailed and has certain reference value. Friends who are interested must finish reading it.
Python ternary operator
The Python ternary operator is used to select one of two values based on the condition. It is a microcosm of the if-else statement, which assigns one of two values to a variable.
The syntax of the Python ternary operator is:
[statement_1] if [expression] else [statement_2]
If the expression evaluates to True, select statement_1. Otherwise, select statement_2 if the expression evaluates to False.
You can provide values, variables, or statements for statement_1 and statement_2.
Tip: the following is the main body of this article. The following examples are available for reference.
Example 1: use the ternary operator to find the maximum of two numbers.
The ternary operator in the following program evaluates to True or False based on the condition a > b to select an or b.
The maximum value of an an if a b is max = an if a > b else b print (max) # 5. Running the program, because a > b returns False, b is selected. Example 2: based on the return value of the condition, Python executes one of the print statements a, b = 2, the triple operator print ('a') if a > b else print ('b') # b III. Example 3: use nested ternary operators Find the maximum of the three numbers a, b, c = 15,93,2 "nested ternary operators max = an if a > b and a > c else b if b > c else cprint (max) # 93 are all the contents of the article" how to use ternary operators in Python ". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!