DEV Community

NoobCoder
NoobCoder

Posted on

How to emulate Ternary Operators of Javascript in Python.

Image description

First For Those Who don't know Ternary Operation

Ternary Operator is a easy and consize way of if-else

Ok So lets flex some JS muscles.

The syntax in JS is something like this.

let v = condition ? "True" : "False"

Here if condition is true.
The value of the variable v becomes True.
While if condition is false.
The value of the variable v becomes False.

In Python's if-else it would be.

if condition:
    v = "True"
else:
    v = "False"
Enter fullscreen mode Exit fullscreen mode

Now To Emulate This in Python ?

ifTrue = "It is a True Value"
ifFalse = "It is a False Value"
trueValue = 432
c1 = [ifFalse, ifTrue][bool(trueValue)]
Enter fullscreen mode Exit fullscreen mode

Understanding The Code

So in simple if else it would be like this

if trueValue:
   c1 = ifTrue
else:
   c2 = ifFalse
Enter fullscreen mode Exit fullscreen mode

So How is this Happening?
Now lets break it into pieces
c1 = [ifFalse, ifTrue] is a List. Do you agree?

c1[0] would be ifFalse.

c2[1] would be ifTrue.

Agreed?
Now,

bool(3) will give True in python

bool(None) will give False in python

Shall We Move on ?

Ok So

a = [ifFalse, ifTrue]
c = a[bool(trueValue)]
Enter fullscreen mode Exit fullscreen mode

here if bool(trueValue) is True then it will get typecasted to integer which is 1.

And, Whats a[1] it's ifTrue.
While it its False. It will get typecasted to a[0] which is ifFalse.

This was a Long One but for short and helpful tricks
Follow PythonZen On Instagram

Try it Here

Top comments (4)

Collapse
 
darkwiiplayer profile image
π’ŽWii πŸ³οΈβ€βš§οΈ

I love this, but at the same time I hate it πŸ˜‚

Reminds me of how you can index arrays in C as 19[arr] (get the 20th element of the arr array) because it just gets translated to *(19+arr)

Is it pretty? No.

Does it make the language look good? No.

Is it fun though? Hell yea!

Collapse
 
vanshcodes profile image
NoobCoder

Yeah, I hated the syntax but loved it at the same time.

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

Why not just do this? πŸ€·β€β™‚οΈ

result = a if condition else b
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vanshcodes profile image
NoobCoder

Actually, I know this is better. But just wanted to show some python power to you