DEV Community

Srinivas for ItsMyCode

Posted on • Originally published at itsmycode.com on

Python Ternary Operator

ItsMyCode |

In Python, Ternary operator, 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 and how we can use it in our code with some examples.

Syntax of Ternary Operator

The ternary operator is available from Python 2.5 onwards, and the syntax is:

[value_if_true] if [expression] else [value_if_false] 
Enter fullscreen mode Exit fullscreen mode

Simpler way to represent ternary operator Syntax

_<expression 1>_  **if**  _<condition>_  **else**  _<expression 2>_ 
Enter fullscreen mode Exit fullscreen mode

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 Operator

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 fullscreen mode Exit fullscreen mode

Output

Enter the marks: 55
The result is Pass
Enter fullscreen mode Exit fullscreen mode

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-else condition.

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

Enter fullscreen mode Exit fullscreen mode

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.

# Python program to demonstrate ternary operator
marks = input('Enter the marks: ')

print("The result is Pass" if int(marks)>=35 else "The result is Fail")

Enter fullscreen mode Exit fullscreen mode

Output

Enter the marks: 34
The result is Fail
Enter fullscreen mode Exit fullscreen mode

The post Python Ternary Operator appeared first on ItsMyCode.

Discussion (0)