Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Rock, Paper, Scissors With Python

DZone 's Guide to

Rock, Paper, Scissors With Python

Get a handle on Conditional, Assignment, and Comparison Operators in Python.

· Web Dev Zone ·
Free Resource

In this article, we will discuss Python Operators and Conditions, their syntax and different ways to use them in order to create a game of Rock, Paper, Scissors. 

Python Operators

Operators are symbols or statements that manipulate the value of operands.

Consider the following example: 10 * 3 = 5.

The integers  "10 " and "3 " are operands (which are also referred to as variables), while "*" is the operator that performs the action of multiplication. It’s important to understand that the use of these operators are not solely limited to operations like addition or multiplication. Some operators can be used for comparisons or to confirm whether a statement is true or false.

For example, in the previous paragraph, I wrote, “The integers ‘10 ’ and  ‘3’ are operands…”. In this example, the word "and" just became the operator, since it compared the two integers. We will be making use of the Logical Operators in one of our games.

The Python language supports the following Operators:

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Identity Operators
  • Membership Operators
  • Bitwise Operators

For examples and in-depth details on these operators, Programiz is an excellent resource that I recommend checking out.

Python Conditional Statements

 Conditional Statements, also referred to as If…else statements are used to control the flow of an operation. In order to accomplish this, we make use of the boolean values true and false — if a statement is true, then do this, otherwise, do this.

To illustrate this let’s start with our basic game of rock paper scissors.

Rock, Paper, Scissors

Rock, Paper, Scissors


We’ll begin by defining a function, "basicRPS" that will take two arguments, Player One's hand (p1) and Player Twos hand (p2). Once we’ve got the basics down, we’ll add a little logic to our game so that we can play against the computer.

def basicRPS(p1,p2):


Our first step is to identify and comment the rules of our game.

#ROCK BLUNTS SCISSORS
#SCISSORS CUTS PAPER
#PAPER COVERS ROCK
#IF PLAYERS CHOOSE THE SAME HAND THEN IT'S DRAW


From our description, we know that there are three options that both users can choose from: Rock, Paper or Scissors. Depending on each player's choice, we will receive a winner. Now, if both users play the same hand, then the result is a draw. Since a draw cancels out the operation, let's use this as our first condition.

if p1.title() == p2.title():
    return 'Draw!'


Assignment and Comparison Operators

You’re probably thinking, "Wait a minute. Why are there two ‘=’ signs?" Well, I’m glad you asked. In Python "=" is considered an Assignment Operator, while "==" is considered a Comparison Operator.

Assignment Operators are used to assign and reassign the value of a given variable. For example:

a = 5
5
a = 2
a
2


We started off by assigning the value of "5" to the variable "a" and then assigned the value of "2" to the same variable.

Comparison Operators tell us if a statement is true or false. Consider the following:

a = 5
b = 5
c = 3
a == b
True
a == c
False


In this example, we assigned the value "5" to both "a" and "b." Then, we asked, "is ‘a’ equal to ‘b’?" To which the program returned true. Before moving on, let’s look at one more example.

a = 5
b = '5'
a == b
False


You’re probably thinking, “If 'a' and 'b' are both '5,' why did Python return false?” Well, it’s simple really. When we assign a value, we also assign the type of value. Take a look.

type(a)
class'int'
type(b)
class'str'

 

When the comparison operator asks if "a" is equal to "b", it’s really asking if "a" is really the same type and value as "b"? By surrounding the "5" with quotation marks, I assigned the type of value to string resulting in false.

With that said, let's get back to our game.

if p1.title() == p2.title():
    return 'Draw!'


We asked, "is Player1’s hand Equaled to Player2’s hand?" We add the "title()" method to account for caps. If the result is true, we return "Draw". If the result is false, the program continues to run. Now, we need to decide what happens if both players make unique calls. We’ll accomplish this using the "elif" statement.

# If the player chooses rock
elif p1.title() == 'Rock' and p2.title() == 'Paper':
    return 'Player 2 won!'

elif p1.title() == 'Rock' and p2.title() == 'Scissors':
    return 'Player 1 won!


By adding our logic we decide, "If player1 chooses rock ‘and’ player2 chooses paper, then player2 wins." By using the "elif" statement, we tell Python, "if the last statement returned false then run this." In Python, the "and" operator is called a Logical Operator. In order for the program to return true, both statements must be true. If either one is false, then the program will return false. From this point, we’ll go ahead and, using the same logic, decide what happens in the event the user chooses paper and scissors.

#If the user chooses paper
elif p1.title() == 'Paper' and p2.title() == 'Rock':
    return 'Player 1 won!

elif p1.title() == 'Paper' and p2.title() == 'Scissors':
    return 'Player 2 won!'

# If the user chooses scissors
elif p1.title() == 'Scissors' and p2.title() == 'Paper':
    return 'Player 1 won!'

elif p1.title() == 'Scissors' and p2.title() == 'Rock':
    return 'Player 2 won!'


There you have it! A basic game of Rock, Paper, Scissors. At this point, we have a pretty good understanding of the logic involved. Let’s take it a step further and adjust our code so that we can play against the computer.

Python Rock, Paper, Scissors

In order for us to play against the computer and have a fair game, we’ll need to import choice from the random module.

The choice model allows us to import a random element from a given list. In our case the list will be one of our three options. Before we implement our logic lets define our function and assign our variables.

from random import choice


def playRPS():
    beats = {'rock' : 'scissors', 'scissors' : 'paper','paper': 'rock'}
    computerHand = beats[choice(['rock','paper','scissors'])]
    playerHand = input('Choose Rock, Paper, Scissors: '


First, we created a dictionary called beats with a key-value pair of outcomes (Key beats Value). Using the same dictionary, we call the choice method on a list of hands that are equal to the keys in the "beats" dictionary. Our last variable, "playerHand" assigns the user input as its value.

As a result of this basic setup, we can implement our logic.

    if beats[playerHand] == computerHand:
        print(f'Computer played {computerHand}')
        return 'Player Wins!'


This may or may not take you a few passes to make sense of.  Let's quickly work our way through this one just in case.

Let's say that the player inputs "rock."

The value for the key "rock" is scissors

If the computer randomly chooses "scissors," then "Player" wins because rock beats scissors. Easy enough right? Now, we just need to add the "elif" statement in the event that the computer wins.

    elif beats[computerHand] == playerHand:
        print(f'Computer played {computerHand}')
        return 'Sorry, Computer Won...'


Just like before, if the value for the key (computer's hand) is the same as the player's hand, then the computer wins. Now, our last step is to account for a draw.

return 'Draw!'


This step is basically to say that if none of the other two statements are true then return "draw." And there you have it! You just programmed an interactive game of Rock, Paper, Scissors.

Conclusion

To recap, we learned that there are many types of Python Operators and Conditional Statements.  We also learned that conditional statements can be used to control the flow of an operation. As a tool, conditional statements are priceless and should be in every programmer's toolkit. We made a basic game of Rock, Paper, Scissors and even stepped it up a notch so that we could play against the computer.

If you enjoyed this article and want to see other projects just like it in the future, please leave a comment below. Until next time!

Topics:
python 3.7.0 ,conditional operator ,assignment operator ,comparison operator ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}