What Are Ternary Conditional Operator In Python?

In this tutorial, we will learn What Are Ternary Conditional Operators In Python where ternary operators are conditional operators which deal with if – else conditions in a single line with all the statements to be executed when if the condition is true or false

Ternary

Ternary Operators

They are the operator used as if else, where a set of code needs to be executed in the place of if else.

let’s take an example.

x = 10
result = "positive" if x > 0 else "negative"
print(result)  # Output: positive

Here we can see how the ternary operator is used to take the decision and perform the action of our choice where we want to execute a certain set of code if we get the condition true then a certain set of code is executed otherwise another set of code is executed.

So for the same, we can also use if else for the same but here we can execute only one line of code in this case but in the case of if else we can execute any number of lines of code.

Example of same using if else

x = 10
if x > 0:
    result = "positive"
else if x< 0:
    result = "negative"
else :
   result = "Zero"
print(result)  # Output: positive

In addition to ternary operator as here one more condition of zero is also added where we can also get if there is any zero is assigned to the variable which means

Here we can see we may also add some more conditions as compared to a ternary operator where in the case of a ternary operator we can only use two conditions that is either true or false.

 

To learn more about ternary operators visit: Ternary operators in Python.

Also, visit Understanding Python Dictionary Slicing – Detailed Tutorial with Examples and Problems to learn more about python

To learn more about different programming languages beta python for programming Solutions their tutorials, Solutions of problems, and the concepts clearing.

Leave a Comment

%d bloggers like this: