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 Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap