The ternary operator in many languages works like so:
x = f() ? f() : g()
Where if f()
is truthy then x
is assigned the value of f()
, otherwise it is assigned the value of g()
. However, some languages have a more succinct elvis operator that is functionally equivalent:
x = f() ?: g()
In python, the ternary operator is expressed like so:
x = f() if f() else g()
But does python have the more succinct elvis operator?
Maybe something like:
x = f() else g() # Not actually valid python
The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands. The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand. Here, + is the operator that performs addition.
Python supports one additional decision-making entity called a conditional expression. (It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.) Conditional expressions were proposed for addition to the language in PEP 308 and green-lighted by Guido in 2005.
A : B . The name "Elvis operator" refers to the fact that when its common notation, ?: , is viewed sideways, it resembles an emoticon of Elvis Presley with his signature hairstyle.
Python does have the elvis operator. It is the conditional or
operator:
x = f() or g()
f()
is evaluated. If truthy, then x is assigned the value of f()
, else x is assigned the value of g()
.
Reference: https://en.wikipedia.org/wiki/Elvis_operator#Analogous_use_of_the_short-circuiting_OR_operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With