In this tutorial, you will learn about the Ternary Operator in python and how to use it in your python application with some examples.
Python’s Ternary operators are conditional expressions that evaluate the given variable or value based on a condition being true or false. Using the ternary operators in if statements make it the shorthand if version.
Syntax for Python Ternary Operator:
var= [on_true] if [expression] else [on_false]
Decoding the ternary operator syntax:
And these operators can be thought of as one-line versions of the if-else statements.
Sample code with Ternary operator in python -1
Input:
a=32 b=23 print("a" if a>b else "b")
Output:
a
Sample code with Ternary operator in python -2
Input:
marks = int(input('Enter marks to check:')) result = "Pass" if int(marks) >= 45 else "Fail" print(f" Result - {result}")
Output:
Enter marks to check: 45 Result - Pass