Python ternary operator (known as Conditional Expression) Example

The ternary operator is know as conditional expression in Python and was introduced in Python 2.5 version.


Syntax:

value_if_true if condition else value_if_false

Let's take a look at an example.

'''
Program: Python ternary operator known 
as Conditional Expression Example

Author  : Code2care.org
Version : v 1.0
Date    : 3rd July 2023 

'''

no1 = 100
no2 = 200

max_number = no1 if no2 > no2 else no2

print(max_number)
Output: 200

Documentation: https://docs.python.org/3/reference/expressions.html#conditional-expressions

Syntax:
conditional_expression ::=  or_test ["if" or_test "else" expression]
expression             ::=  conditional_expression | lambda_expr

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!