我在一个函数中创建了一个文本文件。对于一个学校项目,我必须获取该文本文件,并使用相同的数据放入另一个文本文件“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()
在第一个函数中返回(x,y,z),这是由主函数调用的? 确保主函数将元组分配给某个对象,然后将其作为参数传递给第二个函数。。。你知道吗
简化:
我认为最简单的方法是通过函数参数
但我认为你需要重新考虑解决方案,你可以做一个这样的函数:
当你找到第一个文件的时候就给它打电话
如果可以修改函数签名,请参数化
distance
:def distance(x, y, z):
然后从
main
调用readast
时,获取返回值:x, y, z = readast()
从
main
调用distance
时,将x
、y
和z
作为参数传递:distance(x, y, z)
请注意,有几个名为
x
的局部变量。在多个函数之间不共享局部变量,只共享其值。函数调用将参数的值复制到参数中,然后计算它们的返回值。你知道吗相关问题 更多 >
编程相关推荐