将变量传入和传出函数

Passing variables in and out of functions

我编写了一个小程序来执行以下操作:

我试图将它变成一个函数,这样我就可以对 10 行做同样的事情,这样我就可以绘制所有这些行的像素值而不必 运行 程序10次。
代码如下所示:

from astropy.io import fits
import matplotlib.pyplot as plt
import numpy as np

hdulist = fits.open('xbulge-w1.fits')   #   Open FITS file as image
w1data = hdulist[0].data

height = w1data.shape[0]    #   Inspect height of image
width = w1data.shape[1]

def plot_envelope(image, image_height):
    index = np.random.randint(0, height/2)  #   Select random number in upper half
    row = w1data[index]   #   Look at row number

    local_minima = []

    #   Find local minimum, and add to list of minimum-valued pixels
    for i in range(1, width-1):
        if w1data[index][i-1] > w1data[index][i]:
            if w1data[index][i+1] > w1data[index][i]:
                local_minima.append(w1data[index][i])
        else:
            continue
    return (local_minima, row, index)

plot_envelope(w1data, height)

x1 = range(width)
plt.plot(x1, row, color = 'r', linewidth = 0.5)
plt.title('Local envelope for row ' + str(index))
plt.xlabel('Position')
plt.ylabel('Pixel value')
plt.show()

如果我不使用函数定义(即如果 indexrowlocal_minima 的声明以及嵌套的 for 循环,它工作正常在程序的 main 部分)。使用如图所示的函数定义,它 returns 一个 NameError: name 'local_minima' is not defined 错误。
由于我将这些变量传递到函数之外,难道我不能在程序的其余部分使用它们吗?
我是否遗漏了有关局部变量和全局变量的信息?

当您调用 plot_envelope(w1data, height) 时,您是在告诉函数将 w1data 和高度分别分配给图像和 image_heigth。在函数内部,您应该使用 image 虚拟变量(更改函数内部图像的 w1data)来操作 w1data,该范围仅在函数内部。接下来的事情是你应该在一个变量中得到函数 (return) 的结果: envelope = plot_envelope(w1data, height) 然后 local_minima = envelope[0], row = envelope[1], index = envelope[2].