Python3.x:UnboundLocalError和循环

2024-09-30 01:32:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我相当新的编码,所以任何帮助将不胜感激


Tags: toinyouinputstartssfilewords
2条回答

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

问题在于这个陈述

words_needed += 1

它扩展到

words_needed =  words_needed + 1

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

你必须留下选择

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

  • 坏的和不安全的方法。
    input_words函数的开头添加一行global words_needed

调用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()

相关问题 更多 >

    热门问题