gpt4 book ai didi

python 错误 - unboundLocalError

转载 作者:行者123 更新时间:2023-12-01 06:05:32 26 4
gpt4 key购买 nike

我是编程新手,但我喜欢自然语言(如您所见)。我正在尝试编写一个简单的程序来帮助测试法语现在时动词。但是,在这段代码中,我不断收到错误消息,因为 CorrectAnswers 显然尚未设置为全局变量。有什么想法吗!?

import random

level1=["(manger)","je mange", "tu manges", "il mange", "elle mange", "nous mangeons", "vous mangez", "ils mangent", "elles mangent"]
level2=["(boire)", "je bois", "tu bois", "il boit", "elle boit", "nous buvons", "vous buvez", "ils boivent", "elles boivent"]

correctAnswers=0
blanks = '_' * 8

def getVerb():
verbIndex=random.randint(1,len(level1)-1)
print (level1[verbIndex].split()[0], blanks, level1[0])
ans=input()
while ans==level1[verbIndex].split()[1]:
correctAnswers=correctAnswers+1
print ("Nice one!")
print (correctAnswers)
getVerb()
else:
print ("Bad luck!")
getVerb()


getVerb()

最佳答案

CorrectAnswers=0 超出范围。它们应该位于 getVerb 内部。您也不需要递归。

假设您想测试每个级别和每个问题一次:

import random


level1=["(manger)","je mange", "tu manges", "il mange", "elle mange", "nous mangeons", "vous mangez", "ils mangent", "elles mangent"]
level2=["(boire)", "je bois", "tu bois", "il boit", "elle boit", "nous buvons", "vous buvez", "ils boivent", "elles boivent"]
blanks = '_' * 8

def getVerb():
correctAnswers = 0

# Do each level once
for level in (level1, level2):
level_name, choices = level[0], level[1:]

# Shuffle the choices, this makes sure we only do each question once
random.shuffle(choices)

# Go through all the choices once
for choice in choices:
prefix, suffix = choice.split(' ', 2)
print (prefix, blanks, level_name)

ans = raw_input('Answer: ') # input() if Python 3
while True:
if ans == suffix:
correctAnswers += 1
print ("Nice one!")
print (correctAnswers)

# Got the right answer, break out
break
else:
print ("Bad luck!")
# Change prompt to "Try again" on failure
ans = raw_input('Try again: ') # input() if Python 3


getVerb()

如果您可以通过预分割部分或使用字典来控制 level1/level2 输入,则可以对此进行更多优化。

关于python 错误 - unboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8172643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com