[英]I don't know why I'm getting this error or index out of range. I'm using Python 3.0 in jupyter notebook
[英]Python: list index out of range. I don't know how to fix this
def RPS():
userRPS = input("Rock, paper, or scissors? ")
RPSlist = ["rock", "paper", "scissors"]
computerRPS = RPSlist[randint(1,3)]
print("\nI chose " + computerRPS + ", and you chose " + userRPS)
elif userRPS == "scissors":
if computerRPS == "rock":
print("You lose.")
elif computerRPS == "paper":
print("You win.")
elif computerRPS == "scissors":
print("I chose scissors too. Go again.")
RPS()
else:
print("?")
RPS()
因此,如果我運行else語句,它將打印列表索引超出范圍。 如果用戶和隨機生成器選擇相同的事物,則會發生相同的情況。 我試圖學習如何解決此問題,但是我真的不理解任何解釋。
您應該執行randint(0,2),因為RPSList的索引為零。 這樣可以解決超出范圍的錯誤,但您也應該執行“ if ... else”而不是“ elif ... else”。
一種執行所需操作的更好方法是使用random.choice
。
例如
import random
RPSlist = ["rock", "paper", "scissors"]
print(random.choice(RPSlist))
這樣,您不必擔心列表的長度。
所以那條線變成
computerRPS = random.choice(RPSlist)
同樣, if
沒有前面的if
就不能有elif
。 因此,您只需要將該elif
更改為if
。
進行一些更改:
elif userRPS == "scissors":
應該
if userRPS == "scissors":
和
computerRPS = RPSlist[randint(1,3)]
應該
computerRPS = RPSlist[randint(0,2)]
永遠記住列表索引從0
計數,而不是從1
計數。
提及您的問題的這一部分
我真的不明白任何解釋。
在您編輯之前,您曾質疑過
computerRPS = RPSlist[randint(0,3)]
現在,在編輯新命令后
computerRPS = RPSlist[randint(1,3)]
兩者都會導致列表索引超出范圍嗎?
例如, computerRPS = RPSlist[randint(1,3)]
這可能會產生
RPSlist[1]
RPSlist[2]
RPSlist[3]
但您的RPSlist具有三個從0開始的元素
RPSlist = ["rock", "paper", "scissors"]
^ ^ ^
0 1 2
現在,如果randint(1,3)
給您一個像3這樣的隨機數,您的變量將是
RPSlist[3]
但您是數組沒有任何索引為3的變量。最大索引元素為2
因此,您得到索引超出范圍錯誤
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.