Python Ternary Operator

Ternary Operator

The ternary operator is represented in Python by the keywords if and else. In Python, this ternary operator is used when either one of the options needs to be selected after checking for a condition.

Syntax:

a= first_value if (condition) else second_value

First, the condition will be checked if it’s true then the first value will be assigned to ‘a’ otherwise the second value will be assigned to ‘a’ with the help of a ternary operator.

Example:

>>>a= 10 if 1<2 else 20
>>>print(a)

Output: 10

In this example, we see that ‘a’ will be equal to 10 if the condition, (1<2) is satisfied otherwise it will be equal to 20. 

Since 1 is less than 2, thus the first value will be assigned to the variable ”a’ Ii.e. 10.

While reading a data from the user we use the input() function. This input by default will be in string datatype. If we require it to be in a different datatype then we will have to explicitly convert it into the datatype of out choice using types casting.

Example :

>>>x = int(input(“Enter the first number:”))
>>>y = int(input(“Enter second number:”))
>>>z = x if x<y else y
>>>print(z)

Here if the first value x is less than y i.e. if it satisfies the condition then the output will be x otherwise y The output will depend on the input entered by the user.


Nesting of Conditional Operators:

The ternary operator can be used for comparing more than 2 conditions. We can use the ternary operator to check for multiple conditions at once in a single line of code.

Syntax:

a= first_value if (condition1) else second_value if condition2 else third_value

Example:

>>>a= 10 if 2<1 else 20 if 3<2 else 30
>>>print(a)

Output: 30

In this example, we see that ‘a’ will be equal to 10 if the condition, (1<2) is satisfied otherwise it will be equal to 20. 

Since 1 is less than 2 , thus the first value will be assigned to the variable ‘a’ i.e. 10.

Example :

>>>x = int(input(“Enter the first number:”))
>>>y = int(input(“Enter second number:”))
>>>z = int(input(“Enter third number:”))
>>>max= x if x>y and x>z else y if y>z else z
>>>print(max)

To find out the maximum number here if the first value x is greater than y and z i.e. if it satisfies the condition then the output will be x otherwise we check if y is greater than z, then the output will by y. If both the cases are unsatisfied then the output will be z.

Using these ternary operator helps us keep the code shorter as we do not have to use nested condition statements to do simple tasks.

Leave a Comment

Your email address will not be published. Required fields are marked *