Python: equivalent to Javascript "||" override invalid value

In Javascript, I can do this:

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

This returns 3 if x is an "invalid" value, for example 0, null, false, and returns x otherwise. This is useful for empty arguments, for example. I can do A() and it will be evaluated as 3.

Does Python have an equivalent? I think I could make one of the ternary operator a if b else c , but I wondered what people use for this.

+4
source share
2 answers

You can use or to do the same, but you have to be careful because False can be considered unexpected things in this layout. Just make sure you want this behavior if you decide to do it like this:

 >>> "" 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 
+10
source

Answer or :

 def A(x): return x or 3 
+5
source

Source: https://habr.com/ru/post/1310132/


All Articles