Skip to main content

Python Ternary Operator

Python ternary operarator is one of the special operator. It is not a difficult likelywise Simple if .... Statement, if ....  else: .... Statement and if .... elif: .... Statement. It is a simple and  short method to check whether the condition, executes true and false part depends upon given specified  condition.

Ternary Operator

Ternary operator is one  of the simple conditional operator, Which  executes true part and else part based on the result of express or condtions. we can use variable  to get the resullt of the ternary operators.

Syntax

          true_part if <condition> else else_part

You can easily understand how does the ternary operator is doing its action on python programme.

>>> ternary_result = "It is true part" if True else "It is false part"
>>> print(ternary_result)
It is true part
>>> ternary_result = "It is true part" if False else "It is false part"
>>> print(ternary_result)
It is false part
>>> age = 19
>>> ternary_result = "Age is greater than 18" if age>18 else "Age is less than 18"
>>> print(ternary_result)
Age is greater than 18
>>> age = 17
>>> ternary_result = "Age is greater than 18" if age>18 else "Age is less than 18"
>>> print(ternary_result)
Age is less than 18
>>>