在Python中从一个函数到另一个函数使用局部变量?

2024-10-04 07:35:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个函数中创建了一个文本文件。对于一个学校项目,我必须获取该文本文件,并使用相同的数据放入另一个文本文件“distance”,然后将变量“equation”附加到上一个文本文件中每一行的末尾。但是,我一直在思考如何在第一个函数中使用x,y,z变量,然后在第二个函数中使用它们而不使用全局变量?救命啊!你知道吗

def readast():

    astlist=[]
    outFileA=open('asteroids.txt','w')
    letter=65
    size_of_array=15
    astlist=[]*size_of_array
    for i in range(0,size_of_array):
        x=random.randint(1,1000)
        y=random.randint(1,1000)
        z=random.randint(1,1000)

    outFileA.write ('\n'+chr(letter) + '\t' +(str(x)) + '\t' + (str(y)) +'\t' +(str(z)))
    letter= letter+ 1
    return x,y,z
    outFileA.close()

def distance():

    outFileA=open('asteroids.txt','r')
    outFileD=open('distance.txt','w')
    x= (x**2)
    y= (y**2) #these three variables I need to pull from readast
    z= (z**2)
    equation=math.sqrt(x+y+z)

    for row in range(len(outfileA)):
        x,y,z=outFileA[row]
        outFileD.append(equation)
    outFileD.close()

Tags: of函数txtsizerandomopenarraydistance
3条回答

在第一个函数中返回(x,y,z),这是由主函数调用的? 确保主函数将元组分配给某个对象,然后将其作为参数传递给第二个函数。。。你知道吗

简化:

def distance(x,y,z):

   ....



def main():

   ...
   (x ,y ,z) = readast()
   ...

   distance(x,y,z)

我认为最简单的方法是通过函数参数

def distance(_x, _y, _z):
  outFileA=open('asteroids.txt','r')
  outFileD=open('distance.txt','w')
  x= (_x**2)
  y= (_y**2) #these three variables I need to pull from readast
  z= (_z**2)
  ...

但我认为你需要重新考虑解决方案,你可以做一个这样的函数:

def equation(x, y,z):
   return math.sqrt(math.pow(x,2)+math.pow(y,2)+math.pow(z,2))

当你找到第一个文件的时候就给它打电话

astlist=[]*size_of_array
for i in range(0,size_of_array):
    x=random.randint(1,1000)
    y=random.randint(1,1000)
    z=random.randint(1,1000)
    outFileA.write ('\n'+chr(letter) + '\t' +str(x)+ '\t' +str(y)+'\t' +str(z)+ '\t' +str(equation(x,y,z)))
    letter= letter+ 1
outFileA.close()

如果可以修改函数签名,请参数化distance

def distance(x, y, z):

然后从main调用readast时,获取返回值:

x, y, z = readast()

main调用distance时,将xyz作为参数传递:

distance(x, y, z)

请注意,有几个名为x局部变量。在多个函数之间不共享局部变量,只共享其值。函数调用将参数的值复制到参数中,然后计算它们的返回值。你知道吗

相关问题 更多 >