开发者

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

开发者 https://www.devze.com 2023-01-15 20:12 出处:网络
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'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 w开发者_Go百科rong")
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消