Ternary operator in Python
In this tutorial, you will learn about the Ternary Operator in python and how to use it in your python application with some examples.
Ternary Operator in Python
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:
- if[expression] – A boolean expression that needs to evaluate whether true or false.
- The variable var on the left side of the “=” sign will be assigned to either one of the following:
- on_trueif the boolean expression evaluates to be true.
- on_falseif the boolean expression evaluates to be false.
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:
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1230′,’_blank’)”]
a=32 b=23 print("a" if a>b else "b")
Output:
a
Sample code with Ternary operator in python -2
Input:
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1231′,’_blank’)”]
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