如何在函数外访问这个变量?

How do I access this variable outside the function?

我试图重新使用我在函数中定义的变量,但它一直说特定变量未定义。稍后如何在函数内使用可变斜率?或者如何把它变成一个全局变量?

def linear_fit_detrend(data):
    slope, intercept, r_value, p_value, std_err = stats.linregress(years_trend, data)
    print('slope = ',slope)
    print('intercept =', intercept)
    print('r_value =', r_value)
    print('p_value =', p_value)
    print('stnrd error =', std_err)
    detrended = data - (years_trend*slope+intercept)
    return detrended

#using function

baff_lin = linear_fit_detrend(baff_last_25)

print(slope)

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-15-cec786dbdcb3> in <module>
----> 1 print(slope)

NameError: name 'slope' is not defined

在其他解决方案中:在全局范围内声明变量并在您的函数中使用它。然后它将在函数外访问:

slope = 0

def linear_fit_detrend(data):
    global slope
    slope, intercept, r_value, p_value, std_err = stats.linregress(years_trend, data)
    print('slope = ',slope)
    print('intercept =', intercept)
    print('r_value =', r_value)
    print('p_value =', p_value)
    print('stnrd error =', std_err)
    detrended = data - (years_trend*slope+intercept)
    return detrended

# using function
baff_lin = linear_fit_detrend(baff_last_25)
print(slope)

尝试返回 [detrended,slope]print(baff_lin[1])

另一个解决方案是让你的函数 return 多个值

def linear_fit_detrend(data):
    slope, intercept, r_value, p_value, std_err = stats.linregress(years_trend, data)
    print('slope = ',slope)
    print('intercept =', intercept)
    print('r_value =', r_value)
    print('p_value =', p_value)
    print('stnrd error =', std_err)
    detrended = data - (years_trend*slope+intercept)
    return detrended, slope

#using function

baff_lin, slope_var = linear_fit_detrend(baff_last_25)

print(slope_var)