如何让python在我的代码中识别正确的值?字典

时间:2017-11-13 00:31:21

标签: python dictionary

for i in range(n): 
    while len(dictionary)>0:
        choice = random.choice(list(dictionary.keys()))
        correctAnswer = dictionary[choice]
        print("English: ",choice)
        guess = input("Spanish: ")
        dictionary.pop(choice)
        if guess == correctAnswer:
            print("\nCorrect!\n")
        else:
            print("Incorrect\n")
            wrongAnswers.append(choice)
        break
print("\nYou missed", len(wrongAnswers), "words\n")

嗨,我正在尝试在python上创建一个词汇测试。我的代码一直运行到这个块。程序提示用户猜测后,程序会说它是不正确的,即使它是正确的答案。这段代码中有错误吗?我怎么能绕过这个?

这就是它的样子:
英语:白
西班牙语:blanco
不正确

英语:purple
西班牙语:morado
不正确

谢谢!

完整代码:

def main(): 

import random 
wrongAnswers = [] 

print("Hello, Welcome to the Spanish-English vocabulary test.") 
print(" ")
print("\nAfter the test, this program will create a file of the incorrect answers for you to view")

print("\nTo start, please select from the following options: \nverbs.txt \nadjectives.txt \ncolors.txt \nschool.txt \nplaces.txt") #sk

while True: #SK
    selection = input("Insert your selection: ").lower() #user inputs selection #sk
    if selection == "verbs.txt" or selection == "adjectives.txt" or selection == 'colors.txt' or selection == 'school.txt' or selection == 'places.txt':
        print("You have chosen", selection, "to be tested on.")
        break
    if False:
        print("try again.")
        selection = input("Insert your selection: ").lower()
        break



file = open(selection, 'r') 
dictionary = {}
with file as f:
    for line in f:
        items = line.rstrip("\n").split(",")
        key, values = items[0], items[1:]
        dictionary[key] = values


length = len(dictionary)
print(length,'entries found')

n= int(input("How many words would you like to be tested on: "))
while n > length:
    print("Invalid. There are only" ,length, "entries")
    n= int(input("How many words would you like to be tested on: "))
print("You have chosen to be tested on",n, "words.\n")



for i in range(n): 
    while len(dictionary)>0:
        choice = random.choice(list(dictionary.keys()))
        correctAnswer = dictionary[choice]
        print("English: ",choice)
        guess = input("Spanish: ")
        dictionary.pop(choice)
        if guess == correctAnswer:
            print("\nCorrect!\n")
        else:
            print("Incorrect\n")
            wrongAnswers.append(choice)
        break
print("\nYou missed", len(wrongAnswers), "words\n")


if len(wrongAnswers) > 0:  
 wrong = str(wrongAnswers)        
 output = input("Please name the file you would like you wrong answers to be saved in: ")
 outf = open(output, 'w')
 outf.write(wrong)
 outf.close()
else:
    print("You got all of the problems correct!")

main()

0 个答案:

没有答案