This Python code implements a simple “Rock, Paper, Scissors” game where the user competes against the computer. The user inputs their choice of “rock,” “paper,” or “scissors,” and the computer randomly selects one of these options. The program then compares the choices and prints whether the user wins, loses, or ties.
import random
choices = ["rock", "paper", "scissors"]
user_choice = input("Enter rock, paper, or scissors: ")
computer_choice = random.choice(choices)
print(f"Computer chose: {computer_choice}")
if user_choice == computer_choice:
print("It's a tie!")
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "paper" and computer_choice == "rock") or \
(user_choice == "scissors" and computer_choice == "paper"):
print("You win!")
else:
print("You lose!")
import random
The random module provides functions to generate random numbers and make random choices, which will be used to select the computer’s move.
choices = ["rock", "paper, "scissors"]
This list contains the three possible moves in the game: “rock,” “paper,” and “scissors.”
user_choice = input("Enter rock, paper, or scissors: ")
The input function prompts the user to enter their choice. The input is stored in the user_choice variable.
computer_choice = random.choice(choices)
print(f"Computer chose: {computer_choice}")
random.choice(choices) selects a random element from the choices list. This element is stored in the computer_choice variable. The computer’s choice is then printed.
if user_choice == computer_choice:
print("It's a tie!")
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "paper" and computer_choice == "rock") or \
(user_choice == "scissors" and computer_choice == "paper"):
print("You win!")
else:
print("You lose!")
The program uses a series of if, elif, and else statements to determine the game’s outcome.