Skip to main content
replaced http://stackoverflow.com/ with https://stackoverflow.com/
Source Link
URL Rewriter Bot
URL Rewriter Bot

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 ca if b else c but was wondering what people use for this.

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.

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.

Source Link
Jason S
  • 190.6k
  • 176
  • 637
  • 1k

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

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.