简体   繁体   中英

Python 3 I think I have a type mismatch but can't find it

I'm using Python 3.1 to write a simple game involving naming state capitols. I think I have some kind of type mismatch but I don't know what it is. I think it's when I compare the player's answer to the real answer, but don't know how to make it right.

from random import *
states = {}
print ("Guess State Capitols")

statefile = open("state capitols.csv")
for line in statefile:
    (state,capitol) = line.split(",")
    states[state] = capitol
statefile.close()
guessnum = randint(1,50)
names = list(states.keys())
guess = names[guessnum]
print("What is the capitol of " + guess)   
playerguess = input()
if playerguess == str(states[guess]):
    print("Yes You are right!")
print("No you are wrong")
print(str(states[guess]))

It's at

if playerguess == str(states[guess]):

but I don't know what I am doing wrong, in that even when I have the answer right, it says I'm wrong, but prints the same answer I typed in. I know it's a newbie question, but would appreciate any help. (I also know that the line "no you are wrong" would print in any case, but I'll fix that later).

You can use two "prints" to debug it:

print(playerguess)
print(states[guess])

this should give you the hint.

I would say that when you got your capitol from your csv file you didnt take out the newline.

So maybe this will work:

for line in statefile:
    (state, capitol) = line.strip().split(",")
    states[state] = capitol
statefile.close()

If you have a type mismatch then you will get a traceback with lots of useful information. I'll assume that since you haven't posted one you didn't get a traceback, so it isn't a type mismatch.

When you're trying to find a problem like this you should try printing the repr() of the string:

print(repr(playerguess))
print(repr(states[guess]))

That will show you exactly what is in each string, including any trailing whitespace or newlines.

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