繁体   English   中英

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

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

我正在使用Python 3.1编写一个涉及命名州议会大厦的简单游戏。 我认为我有某种类型的不匹配,但我不知道它是什么。 我认为这是我将玩家的答案与真实答案进行比较的时候,但是不知道如何正确。

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]))

它在

如果playerguess == str(states [guess]):

但是我不知道自己在做什么错,即使我的回答正确,它也说我错了,但是会打印出我输入的答案。我知道这是一个新手问题,但是希望获得任何帮助。 (我也知道在任何情况下都将打印“ no you错”这一行,但稍后会予以解决)。

您可以使用两个“打印件”对其进行调试:

print(playerguess)
print(states[guess])

这应该给您提示。

我想说的是,当您从csv文件中获取国会大厦时,您没有取出换行符。

因此,这可能会起作用:

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

如果您的类型不匹配,那么您将获得包含大量有用信息的回溯。 我假设由于您还没有发布一个,所以您没有得到追溯,所以它不是类型不匹配。

当您尝试查找类似问题时,应尝试打印字符串的repr():

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

这将准确显示每个字符串中的内容,包括任何结尾的空格或换行符。

暂无
暂无

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

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