在赋值之前引用的局部变量'list'

时间:2014-09-26 04:22:30

标签: python

我制作了一个简单的脚本,可以将任何输入文本转换为“代码”,也可以将其翻译回来。它一次只能运行一个单词。

我想让脚本将每个新代码添加到每次打印的列表中。例如,第一次翻译时,"HELLO"变为"lohleci"。第二次,我希望它不仅可以显示"world" = "ldwropx",还可以说明目前为止翻译的所有内容。

我是Python的新手,并通过论坛查找有类似问题的人。我尝试这样做的方式(一个段被删除并放入一个单独的脚本中),我得到一个错误,说“在赋值之前引用了局部变量'列表'。”这是产生错误的代码:

list = "none"
def list():
    word = raw_input("")
    if list == "none":
        list = word + " "
        print list
        list()
    else:
        new_list = list + word + " "
        list = new_list
        print list
        list()
list()

1 个答案:

答案 0 :(得分:5)

您的代码有几个问题,所有这些问题都可以通过更多的知识来解决。

  1. 不要将名称list用于您自己的变量或函数。它是内置Python函数的名称,如果您将该名称用于自己的函数,则无法调用内置函数。 (至少,不是没有使用你不应该学习的高级技巧。)
  2. 你也在为两个不同的东西重复使用相同的名称(list),一个变量一个函数。不要那样做;给他们不同的,有意义的名字,反映他们是什么。例如,wordlist表示包含单词列表的变量,get_words()表示您的函数。
  3. 为什么不使用真正的Python列表,而不是使用名为list的变量来累积一组字符串,而不是实际上一个Python列表?它们的设计完全符合您的要求。
  4. 你使用这样的Python列表:

    wordlist = []
    # To add words at the end of the list:
    wordlist.append("hello")
    # To print the list in format ["word", "word 2", "word 3"]:
    print wordlist
    # To put a single space between each item of the list, then print it:
    print " ".join(wordlist)
    # To put a comma-and-space between each item of the list, then print it:
    print ", ".join(wordlist)
    

    不要过于担心join()函数,以及为什么分隔符(列表项之间的字符串)出现在join()之前。这将进入类,实例和方法,您将在稍后学习。现在,请专注于正确使用列表。

    此外,如果您正确使用列表,则无需执行if list == "none"检查,因为您可以append()添加到空列表以及列表中内容。所以你的代码将成为:

    示例A

    wordlist = []
    
    def translate_this(word):
        # Define this however you like
        return word
    
    def get_words():
        word = raw_input("")
        translated_word = translate_this(word)
        wordlist.append(translated_word)
        print " ".join(wordlist)
        # Or: print ", ".join(wordlist)
        get_words()
    
    get_words()
    

    现在还有一个我建议做的改变。不要每次都在最后调用你的函数,而是使用while循环。 while循环的条件可以是你喜欢的任何东西;特别是,如果你将条件设置为Python值True,那么循环将永远不会退出并永远循环,如下所示:

    示例B

    wordlist = []
    
    def translate_this(word):
        # Define this however you like
        return word
    
    def get_words():
        while True:
            word = raw_input("")
            translated_word = translate_this(word)
            wordlist.append(translated_word)
            print " ".join(wordlist)
            # Or: print ", ".join(wordlist)
    
    get_words()
    

    最后,如果你想提前退出循环(任何循环,而不仅仅是无限循环),你可以使用break语句:

    示例C

    wordlist = []
    
    def translate_this(word):
        # Define this however you like
        return word
    
    def get_words():
        while True:
            word = raw_input("")
            if word == "quit":
                break
            translated_word = translate_this(word)
            wordlist.append(translated_word)
            print " ".join(wordlist)
            # Or: print ", ".join(wordlist)
    
    get_words()
    

    到目前为止,这应解决大部分问题。如果您对此代码的工作方式有任何疑问,请与我们联系。