Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: equivalent to Javascript "||" to override non-truthful value

Tags:

python

In Javascript I can do this:

function A(x) { return x || 3; }

This returns 3 if x is a "non-truthful" value like 0, null, false, and it returns x otherwise. This is useful for empty arguments, e.g. I can do A() and it will evaluate as 3.

Does Python have an equivalent? I guess I could make one out of the ternary operator a if b else c but was wondering what people use for this.

like image 881
Jason S Avatar asked Dec 07 '22 03:12

Jason S


2 Answers

You can use or to do the same thing but you have to be careful because some unexpected things can be considered False in that arrangement. Just make sure you want this behavior if you choose to do it that way:

>>> "" or 1
1
>>> " " or 1
' '
>>> 0 or 1
1
>>> 10 or 1
10
>>> ['a', 'b', 'c'] or 1
['a', 'b', 'c']
>>> [] or 1
1
>>> None or 1
1
like image 147
Daniel DiPaolo Avatar answered Dec 09 '22 15:12

Daniel DiPaolo


The answer is or:

def A(x):
    return x or 3
like image 45
Konrad Rudolph Avatar answered Dec 09 '22 16:12

Konrad Rudolph