2014-02-21 103 views
0

是否有任何簡單的方法可以從一個函數調用另一個函數? 我試圖做出距離/時間/速度轉換程序的輸出應該是這個樣子:從其他函數調用變量

1 Enter the distance [m]: 400 
2 Enter the time [min]: 0.7197 
3 
4 Original distance: 400 m 
5 = 0.2486 mi 
6 = 437.6 yd 
7 = 1312.4 ft 
8 = 15748.0 in 
9 
10 Your distance and time give speeds of: 
11 9.26 m/s, 10.13 yd/s, 33.35 km/hr, and 20.73 mi/hr. 

我到目前爲止是這樣的:

def getInput(): 
    dist=int(input("Enter the distance [m]: ")) 
    time=input("Enter the time [min]: ") 
    convDist(dist,time) 

def convDist(dist,time): 
    miles=dist*.0006214 
    yards=dist*1.094 
    feet=dist*3.281 
    inches=dist*39.37 
    km=dist*.001 
    print("Original distance: ",dist) 
    print("= ",miles," mi") 
    print("= ",yards," yd") 
    print("= ",feet," ft") 
    print("= ",inches," in") 
    print() 
    convTime(time) 


def convTime(time): 
    time=float(time) 
    seconds=time*60 
    hours=time/60 
    calcSpeed(hours,seconds) 

def calcSpeed(hours,seconds): 
    ms=dist/seconds 
    yds=yards/seconds 
    kmhr=km/hours 
    mihr=miles/hours 
    print("Your distance and time give speeds of:\n" 
    ,m,"m/s",yds,"yd/s",kmhr,"km/hr",mihr,"mi/hr") 


def main(): 
    getInput() 

main() 

如果我有問題從第一個函數到calcSpeed()函數獲取數字(輸入),我需要該輸入來計算速度。

+0

將它們添加到列表拉姆達(參數列表) – BRFennPocock

+0

你似乎沒有以往任何時候都可以返回任何東西......有方法的返回值? – Trent

回答

0

將您需要的值傳遞給函數。如果這些值是由中間函數計算的,那麼它們就是return

可以重寫您的函數convTimeconvDist,以便它們具有return語句,並且它們以合適的形式返回您希望在函數外部提供的內容。

def convTime(time): 
    time=float(time) 
    seconds=time*60 
    hours=time/60 
    return {'time':time,'seconds':seconds,'hours':hours} 

然後在您的通話功能

time_dict = convTime(time) 
calcSpeed(dist,time_dict) 

你將不得不改變你的calcSpeed功能相應

0

你嵌套另一個函數內部功能,但你可以只需計算函數中的值並使用return語句將其取出即可。

def getInput(): 
    dist=int(input("Enter the distance [m]: ")) 
    time=input("Enter the time [min]: ") 

    return dist, time 

然後使用從一個函數返回的值作爲下一個函數。

dist,time = getInput() 
miles,yards,feet,inches,km = convDist(dist,time) 

等等...

+0

如果我要求它,這會不會導致它對時間和時間進行重新提示? – Montop20