views:

43

answers:

2

Hi, 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).

+2  A: 

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()
joaquin
That fixed it. I'll have to remember about newline characters. I also didn't know you could 'stack' methods like that. So I learned two things. Many Thanks
chrisfs
A: 

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.

Duncan