为什么Python函数定义中不允许将方法的返回值用作可选参数的值?

为什么Python函数定义中不允许将方法的返回值用作可选参数的值?,python,Python,以下是我的代码: def find_first_occurance(s, c, start=0, end=len(s) ): while start<end: if s[start] ==c: # whether they are the same or not return start else: start+=1 return -1 print(find_first_oc

以下是我的代码:

def find_first_occurance(s, c, start=0, end=len(s) ):

    while start<end:
          if s[start] ==c: # whether they are the same or not
              return start
          else:
              start+=1
    return -1

print(find_first_occurance("the days make us happy make us wise","s"))
def find_first_发生(s,c,start=0,end=len):

当您定义函数时,没有定义start
s
,因此会出现错误

您可以尝试在函数中初始化

def find_first_occurance(s, c, start=0, end=None ):
    if end is None:
        end = len(s)

end=len
?为什么允许这样做?可选参数的默认值是在定义函数时计算的,而不是每次运行时(如JavaScript中)。看看这会带来什么后果。惯用的解决方案是
end=None
如果end为None:end=len
。我同意@Ryan。而在函数定义中,谁将被编译,谁将知道未来的长度。表示在创建字符串之前获取字符串的长度。