简体   繁体   English

Python 3我认为我的类型不匹配,但是找不到

[英]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. 我正在使用Python 3.1编写一个涉及命名州议会大厦的简单游戏。 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]): 如果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). (我也知道在任何情况下都将打印“ no you错”这一行,但稍后会予以解决)。

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. 我想说的是,当您从csv文件中获取国会大厦时,您没有取出换行符。

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: 当您尝试查找类似问题时,应尝试打印字符串的repr():

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

That will show you exactly what is in each string, including any trailing whitespace or newlines. 这将准确显示每个字符串中的内容,包括任何结尾的空格或换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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