Python 3.x:UnboundLocalError和Loop

时间:2015-03-29 18:34:48

标签: python python-3.x

words = []
words_needed = 0


def input_words():
    inputWords = input('Please input more words that you want to play with.').lower()
    words.append(inputWords)
    words_needed += 1
    while words_needed < 5:
        input_words()
    else:
        words_needed >= 5
        input_SS = input('Do you want to continue adding words?')
        if input_SS == 'yes':
            input_words()
        elif input_SS == 'no':
            end

def Start_up():
    start_question = input('Do you want to add your own words to the list?')
    if start_question == 'yes':
        input_words()
    elif start_question == 'no':
        pre_words = (*words in a list*)
        words.extend(pre_words)


Start_up()

当我运行这段代码时,它会永远耗尽,但会带来错误;

Traceback (most recent call last):
  File "F:\A453\Code\Python Hangman\Hangman.py", line X, in <module>
    Start_up()
  File "F:\A453\Code\Python Hangman\Hangman.py", line Y, in Start_up
    input_words()
  File "F:\A453\Code\Python Hangman\Hangman.py", line Z, in input_words
    words_needed += 1
UnboundLocalError: local variable 'words_needed' referenced before assignment

我对编码很新,所以任何帮助都会受到赞赏

2 个答案:

答案 0 :(得分:1)

让我向你解释一下这个问题

问题在于声明

words_needed += 1

它扩展到

words_needed =  words_needed + 1

因此它会在你的函数中创建一个局部变量,但是当你执行words_needed + 1并因此抛出错误时,你试图访问它的值。

你必须选择

  • 标准而准确的方式。
    将您的函数定义为def input_words(words_needed):,将words_needed作为参数传递,无论您在何处调用函数,都将其称为input_words(words_needed)

  • 糟糕且不安全的方式。
    global words_needed功能

  • 的开头添加一行input_words

答案 1 :(得分:0)

当您致电words_needed+=1时,您正试图访问本地范围内的变量words_needed,该范围未定义。因此,您应该传入并返回words_needed,以便随处可访问:

words = []
words_needed = 0


def input_words(words_needed):
    inputWords = input('Please input more words that you want to play with.').lower()
    words.append(inputWords)
    words_needed += 1
    while words_needed < 5:
        input_words()
    else:
        words_needed >= 5
        input_SS = input('Do you want to continue adding words?')
        if input_SS == 'yes':
            input_words()
        elif input_SS == 'no':
            return words_needed
    return words_needed

def Start_up():
    start_question = input('Do you want to add your own words to the list?')
    if start_question == 'yes':
        words_needed = input_words(words_needed)
    elif start_question == 'no':
        pre_words = (["words", "in", "a", "list"])
        words.extend(pre_words)


Start_up()