【发布时间】:2013-03-22 19:49:01
【问题描述】:
所以我一直想知道一些我确信有一个非常简单的答案,但我似乎无法理解它。在一个函数中,我如何设置一个全局变量来执行某个任务。例如,我试过:
def function():
global x
x = input("Name of variable: ")
x = print("Working")
我也试过了:
def function(Name_Of_Variable):
global Name_Of_Variable
Name_Of_Variable = print("Working")
基本上,我只需要能够在函数中设置一个全局变量。我试图开始工作的实际代码是这样的:
def htmlfrom(website_url):
import urllib.request
response = urllib.request.urlopen(website_url)
variable_for_raw_data = (input("What will this data be saved as: "))
global variable_for_raw_data
variable_for_raw_data = response.read()
会发生这样的事情:
>>> htmlfrom("http://www.google.com")
What will this data be saved as: g
>>> g
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
g
NameError: name 'g' is not defined
注意事项:
- Python 3.3
- 全局变量(非本地)
【问题讨论】:
-
我真的很好奇哪个 Python 教程告诉你使用全局变量...
-
您是否尝试过以另一种不需要全局变量的方式解决问题?
-
我还没有遵循 python 教程。据我所知,全局变量只是可以在任何地方访问的变量。为什么它们没有用,或者有没有更有用的方法?请详细说明。不,我没有尝试过另一种方式。有吗?
-
在函数之间传递变量通常更好。
标签: function web python-3.x global-variables