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

时间:2014-11-22 21:19:26

标签: 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()

3 个答案:

答案 0 :(得分:1)

如果您可以修改功能签名,请参数化distance

def distance(x, y, z):

然后当您从readast致电main时,请抓住返回值:

x, y, z = readast()

当您从x致电y时,

并传递zdistancemain作为参数:

distance(x, y, z)

请注意,有几个名为x本地变量。您没有在多个函数之间共享局部变量;只有它的价值。函数调用将参数的值复制到参数中,然后计算它们的返回值。

答案 1 :(得分:1)

你在第一个函数中返回(x,y,z),由main函数调用? 确保你的main函数将元组分配给某个东西,然后将它作为参数传递给第二个函数...

简化为:

def distance(x,y,z):

   ....



def main():

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

   distance(x,y,z)

答案 2 :(得分:0)

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

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()
相关问题