python - Python UnboundLocalError:从字典中选择单词的函数出现问题
问题描述
我编写了一个从字典中选择单个键(=word)的函数。如果该密钥已被使用,则应选择另一个密钥。这是我的功能:
nom_acc = {"qeso":"qes", "os":"os", "sondra":"sondre", "mawizzi":"mawizze", "khewo":"khewe", "alegra":"alegre", "kendra":"kendre", "zhalia":"zhalie", "achrakh":"achrakh", "ador":"ador", "hoggi":"hogge", "soqwi":"soqwe"}
usedWords = []
def wordChoice():
global usedWords
print(usedWords) ### DELETE LATER
word = random.choice(list(nom_acc)) ### randomly pick a key from a dictionary (which is the nominative form)
print(word) ### DELETE LATER
if word in usedWords:
print("gotta pick another word") ### DELETE LATER
wordChoice()
else:
usedWords.append(word)
accusative = nom_acc[word]
return word, accusative
该功能嵌入到主程序中。当我像这样运行代码时,只要选择了一个已经使用过的单词,它就会给我一条错误消息:
UnboundLocalError: local variable 'accusative' referenced before assignment
如果我为单词和宾格变量添加一个虚拟值,它似乎可以工作:
if word in usedWords:
print("gotta pick another word") ### DELETE LATER
word="DUMMY"
accusative="DUMMY"
但我想要的是,如果该词已被使用,则从字典中选择另一个词。我该如何实施?
解决方案
这是调用 wordChoice() 函数的代码部分:
def writeAcc():
'''Minigame: User has to enter the correct accusative form, after three correct answers he passed'''
global isPlaying, usedWords
isPlaying = True
# asking the user to enter the right accusative form of the word
print("Please enter the accusative form of the following words\n")
# player passed when he reached 3 correct answers
right = 0
while right < 4:
word, accusative = wordChoice()
print("Nominative ", word)
print("Need help? Enter 'y' to see the menu again or press the enter-key to continue.")
choice = input("\t\t\tChoice: ")
if choice == 'y':
continueGame = displayMenu()
if not continueGame:
return
print("Nominative ", word)
answer=input("Accusative ")
if answer==accusative:
right+=1
print("Guessed right:", right)
if right < 4 and (len(usedWords) == len(list(nom_acc))):
print("Sorry you don't seem to have what it takes to learn the accusative.")
break
if right == 4:
print("Congratulations! You passed the first step, you will now enter the next challenge.")
推荐阅读
- tensorflow - 自动将类似 Tensorboard 的损失图保存到图像文件中
- c# - C# - System.ArgumentOutOfRangeExceptionSpecified 参数超出有效值范围
- css - 具有未定义宽度的浮动段落
- java - 在方法中使用字符串的值
- php - Wordpress 登录链接不起作用
- javascript - 如何将数字四舍五入到最接近的比例/因子数
- android - 套接字 - 如何?
- angular - 如何将项目 angular4 集成到另一个项目 angular4
- php - 通过 HttpURLConnection POST Android 将变量传递给 PHP
- json - 如何使用 JsonSchema 对复杂模式进行建模而无需太多重复?