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: global name 'numKilos' is not defined ” 我不知道为什么它说 numKilos 没有定义。numKilos 等于用户输入的数字。

4

3 回答 3

3

numKilos是 和 中的局部变量inputKilosconvert_kilos但不是print_output。局部变量只能从该函数内访问。

要传递变量,请使用return <value>从函数返回一个值,然后通过使用收集它result = function(),或者通过将值传递给函数来执行相反的操作(就像您使用convert_kilos.

于 2012-09-23T01:45:39.227 回答
0

Here's a refactored version:

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()
于 2012-09-23T03:09:27.280 回答
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()
于 2012-09-23T02:24:49.903 回答