Python 未定义全局名称“X”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19889493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Global name 'X' not defined
提问by Noah Laster
I looked in all kind of similar questions, but just couldn't find one that fitted my situation (or maybe there is one, but I'm new to programming).
我查看了所有类似的问题,但找不到适合我情况的问题(或者可能有一个,但我是编程新手)。
The version of Python that I use is 2.7.4, and I get in my program the error on line 11: NameError: global name 'opp' is not defined
我使用的 Python 版本是 2.7.4,我在我的程序中遇到了第 11 行的错误: NameError: global name 'opp' is not defined
I wanted to make a calculator for dimensions of floors. Here is my code:
我想制作一个计算地板尺寸的计算器。这是我的代码:
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
Since I now got the answer, I want to share it with you, so here it is:
既然我现在得到了答案,我想和你分享,所以这里是:
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
采纳答案by Ashwini Chaudhary
You should call your function, otherwise opp
will not get defined.
你应该调用你的函数,否则opp
不会被定义。
oppervlakte()
print opp
But a better way would to return opp
from the function and assign to a variable in global namespace.
但是更好的方法是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()
And just calling int()
on a string will not make it an integer, you should assign the returned value to a variable.
并且仅调用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