在函数内定义变量

时间:2017-05-09 10:38:34

标签: python function undefined

我的代码一直有问题

NameError: name 'km' is not defined

我在函数中定义了这个。 如果我使用选择功能这样做会更好吗?

def userinput():
    while True:
        try:
            km = int(input("Enter the amount of kilometres you need (1 or 2)"))
            break
        except ValueError:
            print ("Oops!  That was no valid number.  Try again...")
    return
userinput()
if km >= 3:
    userinput()
if km <= 0:
    userinput()
if km == 1: 
    zone = 0.01862
if km == 2:
    zone = 0.02

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

def userinput():
    while True:
        try:
            km = int(input("Enter the amount of kilometres you need (1 or 2)"))
            break
        except ValueError:
            print ("Oops!  That was no valid number.  Try again...")
    return km

km = userinput()
if km >= 3:
    km = userinput()
if km <= 0:
    km = userinput()
if km == 1: 
    zone = 0.01862
if km == 2:
    zone = 0.02

原因就在于Alnitak说 -

  

变量仅在首次声明它们的范围内可见

希望这对你有帮助,Yahli。