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
我相当新的编码,所以任何帮助将不胜感激
让我给你解释一下这个问题
问题在于这个陈述
它扩展到
因此,它在函数中创建了一个局部变量,但是在执行
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
,以便在任何地方都可以访问它:相关问题 更多 >
编程相关推荐