2012-09-23 170 views
0
def inputKilos(): 

    while True: 
     numKilos = float(raw_input("Enter a number of Kilometers. Enter 0 to end program. ")) 

     if numKilos == 0: 
      break 
     else: 
      convert_kilos(numKilos) 

    return 

def convert_kilos(numKilos): 
    numMiles = numKilos * 0.6214 
    print_output() 
    return 

def print_output(): 
    print numKilos, "kilometers eqauls", numMiles, "miles." 

def main(): 
    inputKilos() 

main() 

當我嘗試運行它說,這個項目「NameError:全局名稱‘numKilos’沒有定義」我不知道爲什麼它說numKilos ISN」定義。 numKilos等於用戶輸入的數字。NameError:全局名稱「numKilos」沒有定義

+0

請添加一個語言標記。 – SLaks

回答

3

numKilosinputKilosconvert_kilos中的局部變量,但不是print_output。局部變量只能從該函數中訪問。

是傳遞變量,使用return <value>通過傳遞值代入函數(如你convert_kilos沒有從函數返回一個值,然後通過使用result = function()收集呢,還是相反。

0

這些都是局部變量。不是全球

你可以試試這個:

#!/usr/bin/python 

def inputKilos(): 
    while True: 
     numKilos = float(raw_input("Enter a number of Kilometers. Enter 0 to end program. ")) 
     if numKilos == 0: 
      break 
     else: 
      miles = convert_kilos(numKilos) 
      print_output(numKilos,miles) 
    return 

def convert_kilos(numKilos): 
    numMiles = numKilos * 0.6214 
    return numMiles 

def print_output(numKilos,numMiles): 
    print numKilos, "kilometers eqauls", numMiles, "miles." 


inputKilos() 

或者使用全局關鍵字:

#!/usr/bin/python 

numKilos=0 
numMiles=0 

def inputKilos(): 
    while True: 
     global numKilos 
     numKilos = float(raw_input("Enter a number of Kilometers. Enter 0 to end program. ")) 
     if numKilos == 0: 
      break 
     else: 
      convert_kilos(numKilos) 
      print_output 

def convert_kilos(numKilos): 
    global numKilos 
    global numMiles 
    numMiles = numKilos * 0.6214  

def print_output: 
    global numKilos 
    global numMiles 
    print numKilos, "kilometers eqauls", numMiles, "miles." 


inputKilos() 
0

這裏有一個重構的版本:

MILES_PER_KM = 0.621371 

def get_float(prompt=''): 
    while True: 
     try: 
      return float(raw_input(prompt)) 
     except ValueError: 
      pass 

def main(): 
    while True: 
     kms = get_float('Enter a distance in kms (or 0 to exit): ') 
     if kms: 
      miles = MILES_PER_KM * kms 
      print ' {} kilometers is {} miles.'.format(kms, miles) 
     else: 
      break 

if __name__=='__main__': 
    main() 
相關問題