5

我查看了所有类似的问题,但找不到适合我情况的问题(或者也许有一个,但我是编程新手)。

我使用的 Python 版本是 2.7.4,我在程序中得到第 11 行的错误:NameError: global name 'opp' is not defined

我想制作一个计算地板尺寸的计算器。这是我的代码:

def oppervlakte():
    global lengte
    global br
    global opp

    lengte = raw_input("Voer de lengte in: ") # Put in the length
    br = raw_input("Voer de breedte in: ") # Put in the width
    opp = lengte * br # Calculates the dimension of the floor
    return int(lengte), int(br) # Makes the variables lengte & br an integer

print opp

既然我现在得到了答案,我想和你分享,所以这里是:

def oppervlakte():
    lengte = raw_input("Voer de lengte in: ") # Asks for the length
    br = raw_input("Voer de breedte in: ") # Asks for the width

    lengte = int(lengte) # String lengte --> int lengte 
    br = int(br) # String br --> int br

    opp = lengte * br # Calculates the dimensions of the floor

    return opp, lengte, br

opp, lengte, br = oppervlakte()
print "De oppervlakte is", opp # Prints the dimension
4

1 回答 1

9

你应该调用你的函数,否则opp不会被定义。

oppervlakte()
print opp

但更好的方法是opp从函数返回并分配给全局命名空间中的变量。

def oppervlakte():
    lengte = int(raw_input("Voer de lengte in: ")) #call int() here
    br = int(raw_input("Voer de breedte in: ")) # call int() here
    opp = lengte * br # Calculates the dimension of the floor
    return opp, lengte, br 

opp, lengte, br = oppervlakte()

并且仅调用int()字符串不会使其成为整数,您应该将返回的值分配给变量。

>>> x = '123'
>>> int(x)       #returns a new value, doesn't affects `x`
123
>>> x            #x is still unchanged
'123'
>>> x = int(x)   #re-assign the returned value from int() to `x`
>>> x
123
于 2013-11-10T12:06:30.787 回答