In Python, the ternary operator is a shorthand way of writing a simple conditional expression. It's also commonly known as the conditional operator. The syntax of the ternary operator is:r
expression_if_true if condition else expression_if_false
condition:
This is the condition that you want to evaluate. If the condition is True, the expression before the if keyword is executed; otherwise, the expression after the else keyword is executed.
This is the condition that you want to evaluate. If the condition is True, the expression before the if keyword is executed; otherwise, the expression after the else keyword is executed.
expression_if_true:
This is the value or expression that will be returned if the condition is True.
This is the value or expression that will be returned if the condition is True.
expression_if_false:
This is the value or expression that will be returned if the condition is False.
This is the value or expression that will be returned if the condition is False.
--------------------------------
Here is a code which uses the ternary operator in python to find maximum of two numbers:
num1 = 7
num2 = 8
max_num = num1 if num1 > num2 else num2
print(max_num)
num2 = 8
max_num = num1 if num1 > num2 else num2
print(max_num)
0 Comments