Python Ternary Operator

In python programming inline if else satement is also used as ternary or conditional operator. Conditional operator in python use a valid relational expression and can return some value to the LValue. This LValue must be a variable. This is also called python ternary if satement.

Ternary operator statement use python ternary expression, This expression does not use any special keyword or operator.

Python ternary syntax:

Synatx of ternary operator in python is as.

Statement  if  expression  else  statement

Example:

# Use of python ternary operator

var = 10
print("Welcome") if var > 10 else print("INSTMS")

Output:

INSTMS

Python ternary assignment:

In python this ternary statement can also be used as ternary assignment. We just have to use a variable on the left side of conditional statement. In this situation we will return value from the ternary statement. It is also called python conditional assignment one line.

Syntax:

variable  = Data/Value if  expression  else  Data/Value

Example:

# Use of python assignment ternary operator

var = 10
x = 0 if var > 10 else var
print(x)

Output:

The output of above python script will be.

10

Python Ternary Operator example

This example script will compare two given variables and display the value of greater variable using ternary operator.

# python script to check
# maximum of two numbers
# using ternary operator

a = 100
b = 150
print("Maximum is:  " + str(a)) if a > b else print("Maximum is:  " + str(b))

Output:

Maximum is:  150
 
 
Comments
Login to TRACK of Comments.