未定义全局名称“X”

2024-06-16 12:27:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我看了所有类似的问题,但就是找不到一个适合我的情况(或可能有一个,但我是新的编程)。

我使用的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

Tags: theinbrinputrawputisdef
1条回答
网友
1楼 · 发布于 2024-06-16 12:27:14

您应该调用函数,否则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

相关问题 更多 >