所以我一直想知道一些我肯定有一个非常简单的答案,但我似乎无法绕过它。在函数中,如何设置全局变量以执行特定任务。例如,我试过:
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
要记住的事情:
答案 0 :(得分:1)
正如评论中所讨论的那样:据我所知,不需要全局变量。 (如果这真的是你认为你需要的话,我会很高兴相信它。)
更加模块化的编程方式是return
变量,从而允许您在函数之间传递数据。 E.g:
import urllib.request # `import` statements at the top! have a look at PEP 8
def htmlfrom(website_url):
''' reads HTML from a website
arg: `website_url` is the URL you wish to read '''
response = urllib.request.urlopen(website_url)
return response.read()
然后假设您要为多个网站运行此功能。您可以将HTML存储在dict
或list
或其他数据结构中,而不是为每个网站创建变量。 E.g:
websites_to_read = ('http://example.com',
'http://example.org',)
mapping_of_sites_to_html = {} # create the `dict`
for website_url in websites_to_read:
mapping_of_sites_to_html[website_url] = htmlfrom(website_url)