## DEV Community is a community of 847,300 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Karan-Munjani

Posted on

# Ternary Operator and Short Circuit Conditionals in Python like JavaScript

If you ever coded in JavaScript then you probably would be aware about content of cover image.

Assuming you are aware that how much ternary operators are useful in programming languages such as C, C++, Go, Perl, Ruby, Java, JavaScript, etc. And Yes Python also Supports Ternary operator.

### Python Introduced Ternary operator in Python 2.5.

It's Called inline-if, Which has syntax something like this:

``````a if condition else b
``````

That Simply means if condition is true then result is a else b.

But if you come from JavaScript Background then it seems odd at first, Cause we are used to code something like this:

``````variable = condition ? a : b
``````

But what if we can familiarize that odd ternary operator to feel like JavaScript one?
Yes We can do that, and that's not a rocket science. We can simply replace the ? with python logical `and` operator and : with logical `or` operator.

Let's See how:

``````variable = condition and a or b
``````

After reading this you might be feel like, "hmmm! that was not much important and useful". But the aim of this article to explain that how logical conditional operators are helpful and just requires a different approach to it.

Also We can use conditional short-circuiting in JavaScript.

``````let data = online && getData();
``````

What it does is if online is true then and then it calls the getData() method.

Short circuiting means that when we are evaluating an AND expression (&&), if the first operand is false it will short-circuit and not even look at the second operand.

So instead code in python like this:

``````if(online):
data = getData()
``````

We can simply use logical `and` again to avoid writing if statement using one liner code:

``````data = online and getData()
``````

Yes I accept that this was not much smart article compare to others but Hope Some Novice programmer will get help form thisðŸ¤ž.