开发英荷翻译答题游戏遇报错:ValueError: tuple.index(x): x not in tuple
问题分析与修复
你的代码存在两个关键问题,直接导致了报错和逻辑错误:
1. 错误获取荷兰语单词
dutch.index(index2) 误用了元组的index()方法——这个方法的作用是查找某个元素在元组中的索引位置,但你传入的是整数index2,而dutch元组里全是字符串,自然找不到匹配项,所以抛出ValueError: tuple.index(x): x not in tuple。
正确的做法是直接用索引访问元组元素:你已经通过eng.index(specialWord)拿到了对应索引,这个索引本身就是整数,不需要额外转换,直接用它取dutch里的对应单词即可。
2. 答案判断逻辑颠倒
你现在的判断条件是userInput == specialWord,这是拿用户输入的荷兰语答案和英语单词对比,完全不符合游戏逻辑,应该和对应的荷兰语单词做对比。
修正后的代码
import random eng = ("castle", "home", "man", "woman", "green") dutch = ("kasteel", "huis", "man", "vrouw", "groen") count = 0 correct = 0 userInput = ' ' def quiz(): global count, correct, userInput while userInput != 'exit': specialWord = random.choice(eng) print('what is the dutch translation for ' + specialWord + '?') # 获取对应索引,直接用索引取荷兰语单词 word_index = eng.index(specialWord) dutchWord = dutch[word_index] userInput = input('Answer: ').lower() # 和荷兰语单词对比判断对错 if userInput == dutchWord: correct += 1 count += 1 print(f"correct: {correct}/{count}") else: count += 1 print(f"Incorrect: {correct}/{count}") # 答错时显示正确答案,提升学习体验 print(f"Correct answer is: {dutchWord}") quiz()
额外优化建议
- 用f-string代替字符串拼接,代码更简洁易读(上面已修改)
- 可以把两个元组合并成一个字典,彻底避免索引处理的麻烦:
word_pairs = { "castle": "kasteel", "home": "huis", "man": "man", "woman": "vrouw", "green": "groen" } # 随机选英语单词 specialWord = random.choice(list(word_pairs.keys())) # 直接取对应荷兰语单词 dutchWord = word_pairs[specialWord]
内容的提问来源于stack exchange,提问作者yjjmtkrle
相关产品推荐
相关产品推荐

