QuakeCore
QuakeCore

Reputation: 1926

one argument default value depends on the len(otherArgument)

def find (myStr,end=len(mystr)):
          ....

The default value of end should be len(myStr), but that doesn't work. The default values are evaluated when the function is defined, not when it is called. When find is defined, myStr doesn't exist yet, so you can't find its length.

Upvotes: 0

Views: 57

Answers (1)

user2555451
user2555451

Reputation:

Why not do something like this:

def find(myStr, end=None):
    end = len(myStr) if end is None else end

Below is a demonstration:

>>> def find(myStr, end=None):
...     end = len(myStr) if end is None else end
...     print end
...
>>> # end is set to the supplied value
>>> find("abc", 10)
10
>>> # end is set to the length of myStr (its default value)
>>> find("abc")
3
>>>

Upvotes: 5

Related Questions