What it does

  1. When you run the script, it will prompt you to enter your choice (rock, paper, or scissors)
  2. It then randomly generate the computer's choice
  3. Moving forward, it compares the choices, and then print the result of the game (win, lose, or tie)

Code Snippet

import random

# Function below is to get and validate user's choice
def get_user_choice():
    # Convert user's choice to lowercase
    user_choice = input("Enter your choice (rock, paper, or scissors): ").lower()

   # Validate it is either "rock", "paper", or  "scissors"
    while user_choice not in ["rock", "paper", "scissors"]:
        print("Invalid choice. Please insert either rock, paper, or scissors.")
        # If invalid, prompt the following for user choice
        user_choice = input("Enter your choice (rock, paper, or scissors): ").lower()
    return user_choice

# Function below is to generate computer's choice randomly
def generate_computer_choice():
    return random.choice(["rock", "paper", "scissors"])

# Function below is to determine who is the winner of the game
def determine_winner(user_choice, computer_choice):
    print(f"You chose {user_choice}.")
    print(f"Computer chose {computer_choice}.")

    if user_choice == computer_choice:
        return "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")
    ):
        return "You win!"
    else:
        return "Computer wins!"

def main():
    print("Welcome to Rock, Paper, Scissors Game!")
    user_choice = get_user_choice()
    computer_choice = generate_computer_choice()
    result = determine_winner(user_choice, computer_choice)
    print(result)

if __name__ == "__main__":
    main()

To run this program

  1. Save code into a .py file, eg: rock_paper_scissors_game.py
  2. run python rock_paper_scissors_game.py
  3. Enter your choice when prompted, and the program will display the result of the game

Built With

Share this project:

Updates