Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One liner Python equivalent of JavaScript like assignment when value is falsey

Consider a function in JavaScript:
If val is not defined in the first call, it becomes 0

function someRecursiveFn (item, val) {
    val = val || 0;
    ...
}

How do I assign the same way in Python?

def someRecursiveFn(item, val):
    val = ??
    ...
like image 243
Om Shankar Avatar asked Jan 13 '16 23:01

Om Shankar


2 Answers

You could use a keyword argument instead of a plain argument to your function:

def someRecursiveFn(item, val=None):
    val = val or 0

so val will default to None if it's not passed to the function call.

the val = val or 0 will ensure that val=None or val='' are converted to 0. Can be omitted if you only care about val being defined in the first place.

like image 77
Geotob Avatar answered Oct 31 '22 22:10

Geotob


val = val if val else 0

#if val is not None, it will assign itself, if it is None it will set val=0

like image 34
Busturdust Avatar answered Oct 31 '22 21:10

Busturdust