2013-03-22 168 views
1

所以我一直在想,我肯定有一个非常简单的答案,但我似乎无法包围我的头。在函数中,如何设置全局变量来执行某个任务。例如,我想:如何在python 3.3中使用input()来设置自己的全局变量?

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 

事情要记住:

  • Pyt汉3.3
  • 全局变量(非本地)
+0

我真正好奇的Python教程告诉你使用全局变量... – bernie 2013-03-22 19:51:59

+0

您是否尝试以另一种方式这不会需要一个全局变量逼近的问题? – bernie 2013-03-22 19:52:36

+0

我没有遵循这个python教程。据我所知,全局变量只是一个可以在任何地方访问的变量。为什么他们不会有用,还是有更有用的方法?请详细说明。不,我没有尝试过另一种方式。有一个吗? – user2070615 2013-03-22 19:58:36

回答

1

正如评论讨论:据我可以告诉有没有必要为一个全局变量。 (如果这真的是你认为你需要的东西,我会很高兴)

一个更模块化的编程方式是return这个变量,因此允许你在函数之间传递数据。例如: -

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存储在dictlist或其他数据结构中,而不是为每个网站创建变量。 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) 
+0

也许在FIRST函数中不需要全局变量,但是当我想要从多个网站获得html时呢?这就是为什么我需要多个变量,对吧? – user2070615 2013-03-22 20:27:21

+0

你不需要多个变量。相反,请考虑将多个网站的HTML存储在'dict','list'或其他数据结构中。 – bernie 2013-03-22 20:34:52

+0

代码如何用字典查看?我不知道如何用字典中的不同变量来存储它们。 – user2070615 2013-03-22 20:41:58