Ternary operator returns one of two expressions depending on a condition.
Syntax
<expression1> if <test condition> else <expression2>
If the test condition evaluates to True, then expression1 gets evalueated, else expression2 gets evaluated.
Example
flag = True
result = 'Turn on the light' if flag else 'Turn off the light'
Find the below working application.
ternary_operator_demo_1.py
flag = True
result = 'Turn on the light' if flag else 'Turn off the light'
print(result)
flag = False
result = 'Turn on the light' if flag else 'Turn off the light'
print(result)
Output
Turn on the light Turn off the light
No comments:
Post a Comment