DEV Community

Cover image for Ternary Operator and Short Circuit Conditionals in Python like JavaScript
Karan-Munjani
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
Enter fullscreen mode Exit fullscreen mode

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

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

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();
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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

data = online and getData()
Enter fullscreen mode Exit fullscreen mode

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

Hope you gained some information from this article✨.

Thank You For reading it out😀

Comment Your Thoughts Below.

Top comments (0)