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
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap