-2

私はPythonの初心者なので、この質問への答えはばかげているかもしれませんが、理解できないようです.

私は単純なじゃんけんゲームを作成しており、random と randint をインポートして、「コンピューター」が行う選択をランダム化していますが、プログラムを 1 回か 2 回実行すると、「IndexError: list index out of range」が発生し始めます。</p>

これを解決するのを手伝ってくれることを願っています。

私のコードのセクションは次のとおりです。

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:
4

3 に答える 3

0

コードの問題は、文字列の後にコンマを配置するのではなく、「紙」文字列にコンマを配置することです。紙とはさみの間にコンマがないため、コンピューターはそれらを 1 つの要素として解釈します。つまり、リストの長さは 3 ではなく 2 です。これが完全なコードです。私はそれが役立つことを願っています:

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!")
于 2021-07-15T11:47:08.297 に答える