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 = ??
    ...
1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.