问题描述
我是 Python 的初学者,所以这个问题的答案可能非常简单,但我似乎无法弄清楚。
我正在制作一个简单的石头剪刀布游戏 并导入 random 和 randint 以随机化“计算机”所做的选择,但在我的程序运行一两次后,它开始给出 'IndexError:列表索引超出范围'
希望你能帮我解决这个问题。
我的一段代码如下:
from random import randint
import time
import sys
#Creating a list of possibilities
x=['Rock','Paper,''Scissors']
#Computer making a random choice
computer=x[randint(0,2)]
#This sets player to false to help in our While loop
player= False
while player==False:
解决方法
x=['Rock','Paper,''Scissors']
这一行有问题——逗号在错误的地方。它在字符串 'Paper,'
内,但应该在 outside。
我建议更改一些内容
在 X 的列表中,逗号位于字符串的中间,您可能希望使用更具描述性的变量名称,如“x”中的名称,将其重命名为类似 “list_of_choices”或“listOfChoices”将是一个好主意:)。 最后,不要使用“randint”函数,您应该使用它的选择函数,它将列表作为参数,并输出一个随机选择。
这是我的实现: 随机导入 导入时间 导入系统
#Creating a list of possibilities
randomChoice = ['Rock','Paper','Scissors']
computersChoice = random.choice(x)
希望这有帮助 :D
,您的代码的问题在于您将逗号与“纸”字符串放在一起,而不是将其放在字符串之后。因为纸和剪刀之间没有逗号,计算机将它们解释为一个元素,这意味着列表的长度为 2,而不是 3。这是完整的代码。希望能帮到你:
from random import choice
# getting input from the user
user_choice = input("Rock,paper or scissors? ").lower()
# printing an error message and quiting the program if the input is invalid
if user_choice != "rock" and user_choice != "paper" and user_choice != "scissors":
print("Error! Invalid answer!")
quit()
# generating the computer's choice
options = ["rock","paper","scissors"]
computer_choice = choice(options)
print("The computer chose",computer_choice)
# checking all of the possible options and declaring who the winner is
if user_choice == computer_choice:
print("You both chose",computer_choice,"therefore it's a tie!")
elif user_choice == "rock" and computer_choice == "paper":
print("Paper beats rock,therefore the computer won!")
elif user_choice == "paper" and computer_choice == "rock":
print("Paper beats rock,therefore you won!")
elif user_choice == "rock" and computer_choice == "scissors":
print("Rock beats scissors,therefore you won!")
elif user_choice == "scissors" and computer_choice == "rock":
print("Rock beats scissors,therefore the computer won!")
elif user_choice == "paper" and computer_choice == "scissors":
print("Scissors beats paper,therefore the computer won!")
elif user_choice == "scissors" and computer_choice == "paper":
print("Scissors beats paper,therefore you won!")