我正在爲一個班級製作一個簡單的程序,叫做「去魚」。列表索引超出範圍,即使輸出正確?
player1Hand = [2, 4, 6, 8, "J", "Q", "K"]
player2Hand = [3, 4, 5, 6, 9, 10, "A"]
player1Guesses = [2, 8, "J", 4, "Q"]
player2Guesses = [6, 9, "A", 5, 3]
基本上有5轉(總共10個輸出)。如果玩家1的猜測在玩家2手中,那麼如果牌不在手中,我應該輸出「這裏是我的卡」和「去掉魚」,反之亦然。我得到它的工作,但我不斷收到索引錯誤。
for i in range(20):
if player1Guesses[i] in player2Hand:
print ("HERE'S MY CARD")
else:
print ("GO FISH")
if player2Guesses[i] in player1Hand:
print ("HERE'S MY CARD")
else:
print("GO FISH")
我試過改變範圍到21和19,但我仍然得到相同的錯誤和輸出。
GO FISH
HERE'S MY CARD
GO FISH
GO FISH
GO FISH
GO FISH
HERE'S MY CARD
GO FISH
GO FISH
GO FISH
Traceback (most recent call last):
File "C:\Users\Allen\Dropbox\Computer Science\GoFish.py", line 8, in <module>
if player1Guesses[i] in player2Hand:
IndexError: list index out of range
我得到正確的輸入,我需要但由於某種原因,它仍然說,索引超出範圍。即使程序正常運行,爲什麼會出現此錯誤?編碼方面我也有點新意,如果你看到任何更容易或更簡單的事情,我可以使用我的代碼隨意指出它!提前致謝!
- avbirm
'範圍(20)'將拋出IndexError,所有列表長度小於10 – haifzhan
你應該使用範圍(5),因爲你有隻有5回合。 – arcticless