我在一個函數中創建了一個文本文件。對於學校項目,我必須取得該文本文件,並使用相同的數據放入另一個文本文件「distance」,然後將變量「equation」附加到前一個文本文件中每行的末尾。然而,我堅持如何在第一個函數中使用x,y,z變量,並在不使用全局變量的情況下在第二個函數中使用它們?幫幫我!在Python中使用另一個函數的局部變量?
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()
你不必做你自己'的距離()'計算,只需使用['math.hypot()'](https://docs.python.org/2/library/math.html?highlight=hypot#math.hypot)函數即可。 – martineau 2014-11-22 21:35:44
何時使用「距離」功能?它是從'readast'調用的嗎? – sleeparrow 2014-11-22 21:37:46
@Adamantite,主函數中調用'distance'函數,這裏沒有顯示。我的教授說每個函數都應該只做一件事,否則我會把追加函數和'readast'放在同一個函數中。距離函數用於創建一個新的文本文件distance.txt,其值與asteroids.txt相同,然後將更多值附加到distance.txt中(如果有意義的話) – Jackie 2014-11-22 21:40:52