定义函数时,非默认参数遵循默认参数

问题描述

代码来自 Here

def cumhist(df,bins=None,title,labels,range = None):
    '''Plot cumulative sum  + Histogram in one plot'''
    if bins==None:
       bins=int(df.YearDeci.max())-int(df.YearDeci.min())
    fig = plt.figure(figsize=(15,8))
    ax = plt.axes()
    plt.ylabel("Proportion")
    values,base,_ = plt.hist( df,bins = bins,normed=True,alpha = 0.5,color = "green",range = range,label = "Histogram")
    ax_bis = ax.twinx()
    values = np.append(values,0)
    ax_bis.plot( base,np.cumsum(values)/ np.cumsum(values)[-1],color='darkorange',marker='o',linestyle='-',markersize = 1,label = "Cumulative Histogram" )
    plt.xlabel(labels)
    plt.ylabel("Proportion")
    plt.title(title)
    ax_bis.legend();
    ax.legend();
    plt.show()
    return

我只添加If 部分。 我收到 n 个错误

  File "<ipython-input-80-07c703baab76>",line 1
    def cumhist(df,range = None):
               ^
SyntaxError: non-default argument follows default argument

我该如何解决这个问题?

解决方法

错误消息意味着您不能在函数的参数列表中的非可选参数之前使用 bins=None。通过删除默认 bins 或将其移动到强制参数之后的位置,使 =None 成为非可选。