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



>我做了一个简单的脚本,可以将任何输入文本转换为"代码",也可以将其翻译回来。它一次只能用一个词。

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

我是 Python 的新手,并且通过论坛查看了有类似问题的人。我尝试这样做的方式(删除了一个片段并将其放入单独的脚本中(,我收到一条错误消息,说"分配前引用了局部变量'list'"。这是产生错误的代码:

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. 不要将名称list用于您自己的变量或函数。它是内置 Python 函数的名称,如果您将该名称用于自己的函数,您将无法调用内置函数。(至少,并非没有诉诸你不应该尝试学习的高级技巧。
  2. 您还将相同的名称(list(用于两个不同的东西,一个变量和一个函数。别这样;给它们不同的、有意义的名字,以反映它们是什么。例如,wordlist用于包含单词列表的变量,get_words()用于您的函数。
  3. 与其使用名为 list 的变量来累积一组字符串,但实际上不是 Python 列表,为什么不使用真正的 Python 列表呢?它们专为您想要做的事情而设计。

你使用像这样的 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()

到目前为止,这应该可以解决您的大部分问题。如果您对任何代码的工作原理有任何疑问,请告诉我。

最新更新