简体   繁体   中英

Python: why does my code keep telling me the answer is wrong when its not?

import random

d = {}
with open('StatesCapitals.txt') as f:
    for line in f:
        key, value = line.split(',')
        d[key] = value



HI = random.choice(list(d.keys()))
print(HI)

answer = (d[HI])

print (answer)

StudentAnswer = (input('Type your answer: '))

if answer.lower() == StudentAnswer.lower():
    print('Correct!')
else:
    print('Wrong.')

This will print out a randomly selected state from my file and also print out the capitol for that state which is the answer to the question. I always receive "wrong" from my else statement no matter if i type the correct answer or not and I cant seem to figure out why.

example of what my StatesCapitals.txt looks like

Iterating through a file returns a string with a newline at the end, so you have to remove it with .strip() . You should replace the 1st line in the loop with key, value = line.strip().split(',') .

As an aside, you don't need to random.choice the list's keys, you can just do answer = random.choice(d) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM