Simple Python Rock, Paper, Scissors Game

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!")

Code Explanation

Import the random module
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.

Define the choices
choices = ["rock", "paper, "scissors"]

This list contains the three possible moves in the game: “rock,” “paper,” and “scissors.”

Get user input
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.

Generate computer’s choice
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.

Determine the outcome
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.

  • If the user’s choice is the same as the computer’s, it’s a tie.
  • If the user’s choice beats the computer’s choice according to the rules of “Rock, Paper, Scissors,” the user wins.
  • Otherwise, the user loses.