9

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 = ??
    ...
Om Shankar
  • 7,989
  • 4
  • 34
  • 54
  • 2
    Possible duplicate of [Python: Assign Value if None Exists](http://stackoverflow.com/questions/7338501/python-assign-value-if-none-exists) – rnevius Jan 13 '16 at 23:44

3 Answers3

9

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.

Geotob
  • 2,847
  • 1
  • 16
  • 26
2

val = val if val else 0

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

Busturdust
  • 2,447
  • 24
  • 41
0

This:

def someRecursiveFn(item, val):
    val = val if val else 0

But the python idiom if val is quite broad as it can have different meanings, some of them could even mean something in a specific context(for example the 0 value), contrarily to an undefined value in javascript.

In python, all the following are considered false:

  • None
  • False
  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a nonzero() or len() method, when that method returns the integer zero or bool value False
arainone
  • 1,928
  • 17
  • 28