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"
ifTrue = "It is a True Value" ifFalse = "It is a False Value" trueValue = 432 c1 = [ifFalse, ifTrue][bool(trueValue)]
So in simple if else it would be like this
if trueValue: c1 = ifTrue else: c2 = ifFalse
So How is this Happening?
Now lets break it into pieces
c1 = [ifFalse, ifTrue] is a List. Do you agree?
c1 would be ifFalse.
c2 would be ifTrue.
bool(3) will give True in python
bool(None) will give False in python
Shall We Move on ?
a = [ifFalse, ifTrue] c = a[bool(trueValue)]
True then it will get typecasted to integer which is 1.
And, Whats a it's
While it its
False. It will get typecasted to a which is
This was a Long One but for short and helpful tricks
Follow PythonZen On Instagram