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()
当我尝试运行该程序时,它说"名称错误:未定义全局名称'numKilos'"我不知道为什么它说未定义numKilos。 numKilos 等于用户输入的数字。
numKilos
在inputKilos
和convert_kilos
中都是局部变量,但不是print_output
。局部变量只能从该函数中访问。
要传递变量,请使用 return <value>
从函数返回值,然后使用 result = function()
收集它,或者通过将值传递到函数中来执行相反的操作(就像您对 convert_kilos
所做的那样。
这些是局部变量,不是全局变量。
你可以试试这个:
#!/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()
这是一个重构版本:
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()