Python Ternary operators also called conditional expressions, are operators that evaluate something based on a binary condition. Ternary operators provide a shorthand way to write conditional statements, which makes the code more concise.
In this tutorial, let us look at what is the ternary operator in Python and how we can use it in our code with some examples.
Syntax of Ternary Operator
The ternary operator is available from Python version 2.5 onwards, and the syntax is:
[value_if_true] if [expression] else [value_if_false]
The simpler way is to represent ternary operator Syntax is as follows:
<expression 1> if <condition> else <expression 2>
Note: The conditionals are an expression, not a statement. It means that you can’t use assignment statements or pass other statements within a conditional expression.
Introduction to Python Ternary Operators
Let us take a simple example to check if the student’s result is pass or fail based on the marks obtained.
Using a traditional approach
We are familiar with “
if-else” conditions lets first write a program that prompts to enter student marks and returns either pass or fail based on the condition specified.
marks = input('Enter the marks: ') if int(marks) >= 35: print("The result is Pass") else: print("The result is Fail")
Enter the marks: 55 The result is Pass
Now instead of using a typical
if-else condition, let us try using ternary operators.
Example of Ternary Operator in Python
The ternary operator evaluates the condition first. If the result is true, it returns the value_if_true. Otherwise, it returns value_if_false
The ternary operator is equivalent to the
If you are from a programming background like C#, Java, etc., the ternary syntax looks like below.
if condition: value_if_true else: value_if_true
condition ? value_if_true : value_if_false
However, In Python, the syntax of the ternary operator is slightly different. The following example demonstrates how we can use the ternary operator in Python.
marks = input('Enter the marks: ') print("The result is Pass" if int(marks)>=35 else "The result is Fail")
Enter the marks: 34 The result is Fail