Python – Rock paper scissors

In this post we will be creating the rock paper scissors game in Python, to help us achieve this we will make use of the random module which implements pseudo-random number generators for various distributions.

The rules of the game are simple and known across the world, although if you don’t know see the below.

  1. Rock beats scissors.
  2. Scissors beats paper.
  3. Paper beats rock.
  4. If the same are chosen by both players, the game is a tie.

See the sample of Python code below where we create the rock paper scissors game. We start by creating a list that will contain all possible options, the user is then required to enter their choice via input. We then validate the user input against our list of options. The script will then pick its own random choice from the list and the game rules are applied.

At the end a winner is declared with the choices revealed to the player.

import random

options = ["rock", "paper", "scissors"]

while True:
    user_choice = input("Enter your choice: ")

    if user_choice not in options:
        print("Invalid choice! Please try again.")
        exit()

    computer_choice = random.choice(options)

    if user_choice == computer_choice:
        print("It's a tie!")
    elif user_choice == "rock" and computer_choice == "scissors":
        print("You win!")
    elif user_choice == "paper" and computer_choice == "rock":
        print("You win!")
    elif user_choice == "scissors" and computer_choice == "paper":
        print("You win!")
    else:
        print("The computer wins!")

    print("You chose", user_choice)
    print("The computer chose", computer_choice,"\n")

Some example games can be seen below.

Enter your choice: rock
It's a tie!
You chose rock
The computer chose rock

Enter your choice: paper
You win!
You chose paper
The computer chose rock
>>>

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply