2014-11-22 90 views
0

我在一個函數中創建了一個文本文件。對於學校項目,我必須取得該文本文件,並使用相同的數據放入另一個文本文件「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() 
+0

你不必做你自己'的距離()'計算,只需使用['math.hypot()'](https://docs.python.org/2/library/math.html?highlight=hypot#math.hypot)函數即可。 – martineau 2014-11-22 21:35:44

+0

何時使用「距離」功能?它是從'readast'調用的嗎? – sleeparrow 2014-11-22 21:37:46

+0

@Adamantite,主函數中調用'distance'函數,這裏沒有顯示。我的教授說每個函數都應該只做一件事,否則我會把追加函數和'readast'放在同一個函數中。距離函數用於創建一個新的文本文件distance.txt,其值與asteroids.txt相同,然後將更多值附加到distance.txt中(如果有意義的話) – Jackie 2014-11-22 21:40:52

回答

1

如果你可以修改函數簽名,參數distance

def distance(x, y, z):

那麼當你從main調用readast,搶返回值:

x, y, z = readast()

和通過x,y,並且z當你從main調用distance參數:

distance(x, y, z)

注意,有幾個地方變量命名x。您不在多個函數之間共享局部變量;只有它的價值。函數調用將參數的值複製到參數中,然後評估其返回的值。

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() 
1

你正在返回(x,y,z)的第一個函數,其中被主函數調用? 確保您的主要功能分配的元組的東西,然後將它作爲參數傳遞到第二函數...

簡化:

def distance(x,y,z): 

    .... 



def main(): 

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

    distance(x,y,z) 
相關問題