Python Tutorial: How to code rock paper scissors in Python

Introduction

Rock Paper Scissors is a popular game that has been played for generations. It is simple, yet entertaining and can be played by anyone. In this Python tutorial, we will show you how to code the game of rock paper scissors using Python.

Python is a high-level programming language that is known for its simplicity and readability. It is widely used in various fields such as web development, data science, and machine learning. Python is also an excellent choice for beginners who are just starting to learn how to code.

In this tutorial, we will assume that you have basic knowledge of Python programming concepts such as variables, loops, and conditional statements. If you are new to Python, don’t worry! We will explain each step in detail so that you can follow along even if you are a beginner.

By the end of this tutorial, you will have created a simple rock paper scissors game using Python. So let’s get started, we’ll use python code blocks like the one below to explain our progress.


# Python code block starts here

# Code example goes here

# Python code block ends here

Rules of Rock Paper Scissors

Rock Paper Scissors is a classic hand game played between two people. The game consists of each player making one of three hand gestures representing either rock, paper, or scissors. The winner is determined by the rules below:

– Rock beats scissors
– Scissors beats paper
– Paper beats rock

In Python, we can create a simple program to play Rock Paper Scissors against the computer. We will use the random module to generate the computer’s choice and then compare it to the user’s choice.

Getting Started: Setting Up the Game

To start coding rock paper scissors in Python, we need to first set up the game. This includes importing any necessary modules and defining the variables we will use throughout the game.

First, let’s import the random module which we will use to generate the computer’s choice of rock, paper, or scissors:


import random

Next, we will define a list of the three possible choices: rock, paper, and scissors:


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

Now that we have our choices defined, we can move on to setting up the game loop. We want the game to continue until the player chooses to quit, so we will use a while loop that runs as long as a certain condition is true:


while True:
    # Game code goes here

Inside this loop, we will prompt the player to make their choice by asking for input:


player_choice = input("Choose rock, paper, or scissors: ")

We also want to validate that the player’s input is one of the valid choices. We can do this by checking if their choice is in our list of choices:


while player_choice not in choices:
    player_choice = input("Invalid choice. Choose rock, paper, or scissors: ")

Finally, we will generate a random choice for the computer using the random.choice() function:


computer_choice = random.choice(choices)

With these basics set up, we can move on to coding the logic for determining who wins each round of rock paper scissors!

Creating a Function to Play the Game

In order to play the rock paper scissors game, we need to create a function that will take in the player’s choice as an input and generate a random choice for the computer. We can use the `random` module in Python to generate a random choice for the computer.

Here’s how we can create a function to play the game:


import random

def play_game(player_choice):
    choices = ['rock', 'paper', 'scissors']
    computer_choice = random.choice(choices)
    
    if player_choice == computer_choice:
        return "It's a tie!"
    
    if player_choice == 'rock':
        if computer_choice == 'paper':
            return "You lose! Paper covers rock."
        else:
            return "You win! Rock smashes scissors."
        
    elif player_choice == 'paper':
        if computer_choice == 'scissors':
            return "You lose! Scissors cut paper."
        else:
            return "You win! Paper covers rock."
        
    elif player_choice == 'scissors':
        if computer_choice == 'rock':
            return "You lose! Rock smashes scissors."
        else:
            return "You win! Scissors cut paper."

Let’s break down this function. First, we import the `random` module. Then, we define our function `play_game` which takes in the player’s choice as an argument.

Inside the function, we create a list of choices – rock, paper, and scissors. We then use `random.choice(choices)` to generate a random choice for the computer.

Next, we check if the player’s choice is equal to the computer’s choice. If it is, we return “It’s a tie!”

If it’s not a tie, we check all possible scenarios where the player can win or lose based on their choice and the computer’s choice. For example, if the player chooses rock and the computer chooses paper, the player loses and we return “You lose! Paper covers rock.”

We repeat this process for all possible scenarios and return the appropriate message based on the outcome of the game.

Now that we have our function, we can use it to play the game by calling `play_game(player_choice)` and passing in the player’s choice as an argument.

Handling User Input

Handling user input is an essential part of any interactive Python program. In the game of Rock Paper Scissors, we need to take input from the user for their move choice.

To handle user input in Python, we use the `input()` function. The `input()` function takes a string as an argument, which is used as a prompt to the user. It waits for the user to enter some text and hit the Enter key.

Here’s an example of using the `input()` function to get the user’s name:


name = input("What is your name? ")
print("Hello, " + name + "!")

In this example, we’re prompting the user with the question “What is your name?” and storing their response in the variable `name`. We then use string concatenation to print out a personalized greeting.

Now let’s use `input()` to get the user’s move choice in our Rock Paper Scissors game:


move = input("Enter your move (rock/paper/scissors): ")

Here, we’re prompting the user with the question “Enter your move (rock/paper/scissors):” and storing their response in the variable `move`.

It’s important to note that whatever text the user enters will be treated as a string. So if we want to compare their move choice with our computer-generated move, we need to make sure they match exactly. We can use conditional statements like `if/elif/else` to check for this.

We’ll cover more on conditional statements in the next section of this tutorial.

Determining the Winner

After both the player and the computer have made their choices, we need to determine the winner. This can be done with a simple set of conditional statements.

First, let’s define the possible outcomes. Rock beats scissors, scissors beat paper, and paper beats rock. We can create a dictionary to store these outcomes:


outcomes = {
    "rock": "scissors",
    "scissors": "paper",
    "paper": "rock"
}

Next, we can check who won by comparing the player’s choice to the computer’s choice and checking if it beats the other choice according to our `outcomes` dictionary. Here’s an example:


if outcomes[player_choice] == computer_choice:
    print("You win!")
elif outcomes[computer_choice] == player_choice:
    print("Computer wins!")
else:
    print("It's a tie!")

In this example, we first check if the player’s choice beats the computer’s choice by looking up the value in `outcomes`. If it does, we print “You win!”. If not, we move on to check if the computer’s choice beats the player’s choice using `outcomes`, and if it does, we print “Computer wins!”. Otherwise, it must be a tie and we print “It’s a tie!”.

And that’s it! With these concepts in mind, you should be able to code your very own rock paper scissors game in Python.

Playing Again

Playing Again:

After the game is finished, we can ask the user if they want to play again. If the user wants to play again, we can simply call the `play_game()` function again. However, before doing so, we need to make sure that we reset the values of `player_score` and `computer_score` to 0.

Here’s how we can modify our `play_game()` function to include the option of playing again:


def play_game():
    player_score = 0
    computer_score = 0
    
    while True:
        # game code
        
        # ask user if they want to play again
        play_again = input("Do you want to play again? (y/n): ")
        
        if play_again.lower() != 'y':
            break
        
        # reset scores
        player_score = 0
        computer_score = 0
        
    print("Thanks for playing!")

In this modified version of `play_game()`, we have added a `while` loop that will continue running until the user chooses not to play again. Inside the loop, we first ask the user if they want to play again using the `input()` function and store their response in a variable called `play_again`.

If the user enters anything other than ‘y’ (meaning they don’t want to play again), we break out of the loop and print a message thanking them for playing.

If the user enters ‘y’, we reset both `player_score` and `computer_score` back to 0 and start a new game.

With this modification, our game now has the option of playing multiple rounds without having to run the code again each time.

Conclusion

In this tutorial, we have learned how to code the popular game of rock paper scissors in Python. We started by defining the rules of the game and then proceeded to write the code step by step.

We began with importing the necessary modules and defining the variables to store user input and computer choice. We then used conditional statements and nested if-else loops to compare the choices and determine the winner.

We also added a loop to allow the user to play multiple rounds and keep track of their score. Finally, we added error handling to ensure that the user inputs a valid choice.

It is important to note that there are many ways to approach coding rock paper scissors in Python. This tutorial is just one example and can be modified or improved upon based on individual preferences.

Overall, this tutorial provides a solid foundation for beginners to learn basic programming concepts such as variables, conditional statements, loops, and error handling. With this knowledge, you can further explore the vast world of Python programming and develop more complex applications.

I hope you found this tutorial helpful and informative. Happy coding!
Interested in learning more? Check out our Introduction to Python course!


How to Become a Data Scientist PDF

Your FREE Guide to Become a Data Scientist

Discover the path to becoming a data scientist with our comprehensive FREE guide! Unlock your potential in this in-demand field and access valuable resources to kickstart your journey.

Don’t wait, download now and transform your career!


Pierian Training
Pierian Training
Pierian Training is a leading provider of high-quality technology training, with a focus on data science and cloud computing. Pierian Training offers live instructor-led training, self-paced online video courses, and private group and cohort training programs to support enterprises looking to upskill their employees.

You May Also Like

Data Science, Tutorials

Guide to NLTK – Natural Language Toolkit for Python

Introduction Natural Language Processing (NLP) lies at the heart of countless applications we use every day, from voice assistants to spam filters and machine translation. It allows machines to understand, interpret, and generate human language, bridging the gap between humans and computers. Within the vast landscape of NLP tools and techniques, the Natural Language Toolkit […]

Machine Learning, Tutorials

GridSearchCV with Scikit-Learn and Python

Introduction In the world of machine learning, finding the optimal set of hyperparameters for a model can significantly impact its performance and accuracy. However, searching through all possible combinations manually can be an incredibly time-consuming and error-prone process. This is where GridSearchCV, a powerful tool provided by Scikit-Learn library in Python, comes to the rescue. […]

Python Basics, Tutorials

Plotting Time Series in Python: A Complete Guide

Introduction Time series data is a type of data that is collected over time at regular intervals. It can be used to analyze trends, patterns, and behaviors over time. In order to effectively analyze time series data, it is important to visualize it in a way that is easy to understand. This is where plotting […]