簡體   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