Skip to content

Instantly share code, notes, and snippets.

@keithdhd
Last active February 26, 2023 14:05
Show Gist options
  • Select an option

  • Save keithdhd/a4de0856a2b4ba156bd8b8a4516d621e to your computer and use it in GitHub Desktop.

Select an option

Save keithdhd/a4de0856a2b4ba156bd8b8a4516d621e to your computer and use it in GitHub Desktop.
Rock, paper, scissors (Instructor notes)

Rock, paper, scissors

Instructor Notes

Learning Objectives

  • Learn how to decompose a problem
  • Practice logical reasoning
  • Know how to work with lists
  • Know how to use functions
  • Know how to get user input for a program
  • Know how to use iteration

Contents

Working out the logic of the gameplay: an unplugged approach

A key part of programming rock, paper, scissors is figuring out all of the possible outcomes of the game. This involves some logical reasoning. You can use the unplugged approach to help you.

In the spirit of unplugged, the activity should be as kinaesthetic as possible. If you are going to create a rock, paper, scissors game, why not play it in real life first?

After you have played a few games, work with the students to create a table to record all of the possible outcomes. Here is a completed table.

Player 1 Player 2 wins
1 Rock Paper Player 2 wins
2 Rock Scissors Player 1 wins
3 Paper Rock Player 1 wins
4 Paper Scissors Player 2 wins
5 Scissors Rock Player 2 wins
6 Scissors Paper Player 1 wins
7 Rock Rock Draw
8 Paper Paper Draw
9 Scissors Scissors Draw

If you were doing this with your learners, you could provide varying levels of scaffolding depending on their ability. High-ability learners could have a piece of paper without a table. Low-ability learners could be provided with a half-completed table. This is a great opportunity to differentiate.

Developing an algorithm

Using the table that you have created, you can begin to think about an algorithm for the conditions that will need to be checked to determine the outcome of the game. The table will help you structure your statements. You might start by writing a few lines of pseudocode for each outcome like the algorithm below and get the students to complete it in pairs:

Get / generate player 1 action
Get / generate player 2 action

If player 1 has rock and player 2 has paper then
  Output "player 2 wins"
If player 1 has rock and player 2 has scissors then
  Output "player 1 wins"
If player 1 has paper and player 2 has rock then
  Output "player 1 wins"
If player 1 has paper and player 2 has scissors then
  Output "player 2 wins"
If player 1 has scissors and player 2 has rock then
  Output" player 2 wins"
If player 1 has scissors and player 2 has paper then
  Output "player 1 wins"
If player 1 has rock and player 2 has rock then
  Output "Draw"
If player 1 has paper and player 2 has paper then
  Output "Draw"
If player 1 has scissors and player 2 has scissors then
  Output "Draw"

This algorithm represents one of several solutions. If you implemented this in Python, it would probably work, but it wouldn’t be very efficient.

There are ways that we can simplify this code and get the same outcome. With your learners, you would look for repeated actions and other ways to write this algorithm.

The easiest one to spot is that three outcomes result in a draw. The three “if” statements could be reduced to one by checking whether player 1’s choice is equal to player 2’s choice.

If player 1 has the same as player 2 then
  Output "Draw"

The next thing, which is more challenging to spot, is the need for so many outcomes. Ask your students to think about these questions:

If player 1 wins, who loses? If player 1 loses, who wins? If player 1 hasn’t won, and it is not a draw, what must the outcome be?

Just focusing on player 1 winning will help you reduce your algorithm further. You can then use an “else” to say that player 2 has won.

Get / generate player 1 action
Get / generate player 2 action

If player 1 has the same as player 2 then
  Output "Draw"
If (player 1 has rock and player 2 has scissors) OR (player 1 has paper and player 2 has rock) OR (player 1 has scissors and player 2 has paper) then
  Output "player 1 wins"
Else
  Output "player 2 wins"

Allowing the computer to make a choice: getting started with the code

Now that your students have an understanding of the logic that underpins the rock, paper, scissors game, the next step is to look at how to build it using code. In this step you will cover:

  • Naming conventions
  • Lists
  • Libraries

The concepts covered in this step would be well suited to a live-coding activity.

Live Coding

Naming conventions

It’s always a good idea to promote sensible naming conventions with your learners early on in a programming project.

Naming conventions are rules that are applied when naming elements in your code such as functions and variables. It is helpful to everyone reading the code that these rules are applied consistently throughout. As educators we should be recommending and modelling sensible naming conventions to our learners.

Naming conventions vary slightly from language to language, but there are many handy guides and references out there. The website Real Python has a useful guide on naming variables, and it reads: “Use a lowercase single letter, word, or words. Separate words with underscores to improve readability”.

It’s worth highlighting that single-letter variable names are not considered best practice as it should be easy to identify what the purpose of the variable is.

Examples:

user_score  = 0   # Good example

User_score = 0  # Not good because it uses capital letters

x = 0  # Not advised, as it is not clear what the purpose of the variable x is

Lists

Your program will use the words “rock, paper, scissors” frequently. This means it’s sensible to structure these three words in a list. This code shows you how the three words can be stored in a list in Python:

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

print(rps_choices[1])

Following the PRIMM approach, predict with your learners what the code will do and document your thoughts and reasoning. Then run the code and compare your findings to your prediction.

To help develop the concept of lists and index positions of the values, investigate the list further by editing the print statement with different values.

print(rps_choices[3])

print(rps_choices[0])

print(rps_choices[-1])

print(rps_choices[4])

print(rps_choices[0,1])

Libraries

Now that you have explored the concept of lists and accessing different values from within a list, the next step is to find a way for the computer to make its choice at random, so that the computer will play against you. You could spend a long time trying to write code that will achieve this yourself, but in the same way as there’s usually “an app for that” for our phones, when coding it’s often the case that someone has built “a library for that”.

Use the random library, and specifically the randint() function within it, to help generate a random integer. The following line of code should be placed on the first line of the program. It is not essential that it is placed on the first line, but it must be before the function is called, and it also helps make the code readable.

from random import randint

# Add the following lines of code below the list.

random_choice = randint(0,2)

print(random_choice)

computer_choice = rps_choices[random_choice]

print(computer_choice)

There are a few ways in which you can use this code to explore its functionality with learners:

Suggestion 1: Run the first two lines of the code above three or four times and observe the value printed out. Be aware that random_choice will hold the current random integer, and not all three.

Suggestion 2: Start off by having the two arguments inside of the randint function to be within a larger range, i.e. randint(1,300). Explore what happens when one of the arguments to randint changes.

Suggestion 3: Once comfortable with the randint function, think of other cases or problems where you would use randint.

Allowing the user to make a choice

Now that you have a program that randomly picks a value from the list and gives you the computer’s choice, you need to start thinking about turning the code into a game. In this step you will cover the following:

  • Functions
  • User input

Functions

Start by adding a line of code that defines the function that has been called game. The rest of the code will need to be indented and the function will have to be “called” for the function to run.

def game(): # defines a function to store the game play code

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

   random_choice = randint(0,2)

   computer_choice = rps_choices[random_choice]

   print(computer_choice)


game() # calls the function when it is needed by the program

Here’s a suggestion. If you were teaching this to your class and the learners hadn’t previously been introduced to the concept of functions, this would be an opportunity to make this into a worked example, to help learners build a schema that they could use when they go on to develop this code further.

A function is something that you might end up using more than once in your program. Here is an example showing how a function can be used if you want to play a game three times:

for i in range(3):
    game() # the game function is called three times

User input

You’re now going to add a human player instead, by capturing some input from the user. One technique you may have previously encountered is the input function:

player = input()

The question is, what are you expecting the user to input? What could be the problem with asking for the user to input “rock, paper, or scissors”? You might suggest that the user might spell the words incorrectly. You might also think about how we have the answers stored in a list; how do we access values from that list?

It’s always a good idea to give the user guidance on what input you are expecting, so in this instance you could create a menu through three simple print statements that you would place within your game() function.

Place the following code at the top of the game() function before the user input:

print("Type 0 for rock")
print("Type 1 for paper")
print("Type 2 for scissors")

You are now ready to ask for and store a user input, but the problem you would face, if you were to use the same input structure as above, is that you’re expecting the answer to be an integer. Unless you tell it otherwise, the input will be handled as a string, even if the user uses the numbers on their keyboard. Therefore you must instruct the computer to change, or cast, the input to an integer, if you are to use the value later on to access your list.

player = int(input("--> ")) # int is added before the input to cast the data type as an integer

Pair Programming Exercise

Now that you have the variable player that is holding the user input, you have a challenge:

  • Make a variable called player_choice that will use the player variable to access the list
  • Add two print statements that show the user what they picked and what the computer picked. They must be well formatted, for example “the computer chose: rock”

Selecting the winner

You have at this stage a working function that:

  • Picks a value at random from a list
  • Accepts user input and uses it to pick an item from a list
  • Prints out the computer’s and the player’s choices

Our current code looks like this:

from random import randint
 
rps_choices = ["Rock", "Paper", "Scissors"]

def game():
    print("Type 0 for Rock")
    print("Type 1 for Paper")
    print("Type 2 for Scissors")
    player = int(input("--> ")) 
    player_choice = rps_choices[player]
    random_choice = randint(0,2)
    computer_choice = rps_choices[random_choice]

    print("You selected: "+player_choice)
    print("The computer selected: "+computer_choice)
    
game()  

We have at this stage a working function that:

  1. Picks a value at random from a list
  2. Accepts user input and uses it to pick an item from a list
  3. Prints out the computer’s and the player’s choices

In this step you are going to use selection (“if” statements) to find out who has won the game.

Here is a Parson’s Problem for your students to solve. Rearrange the lines of code below to create a working segment of code that will:

  • Check whether it was the computer or the user that won
  • Print out an appropriate message informing the user who won
print("You win :)")
print("You win :)")
print("You win :)")
print("The computer wins :(")
print("draw ")

else:

elif player_choice == "scissors" and computer_choice == "rock":

if player_choice == computer_choice:

elif player_choice == "rock" and computer_choice == "scissors":  

elif player_choice == "paper" and computer_choice == "rock":

With this particular problem, the lines not only need to be reordered, but you also need to consider indentation. This could be done on paper or as a group; alternatively you could complete this at the computer so that you can run the code to check if you have the correct solution.

Solution

if player_choice == computer_choice:
  print("draw ")

elif player_choice == "rock" and computer_choice == "scissors":
  print("You win :)")

elif player_choice == "paper" and computer_choice == "rock":
  print("You win :)")

elif player_choice == "scissors" and computer_choice == "paper":
  print("You Win :)")

else:
  print("The computer wins :(")

Ask your students where they think this block of code would go inside the rock, paper, scissors game you have been writing? Get them to have a go themselves and run the program to see whether it informs you who has won.

You’ve now created a basic rock, paper, scissors program and students should be feeling a nice sense of achievement.

Introducing rounds to the game

Currently, your game will run for only one round, and if the user wants to continue playing, you need to rerun your program.

By adding a condition-controlled loop, you can tell the program to keep running your game function until the user decides they want to stop playing.

This step involves:

  • Iterating the game using a condition-controlled loop
  • Ensuring validity of a user response using the .upper() function
  • Condition-controlled loops
  • A while loop is a condition-controlled loop as it will keep iterating while a condition evaluates to True.

while (some condition):

while True:

The code above is often known as a forever or infinite loop.

This will keep iterating forever, because the condition “True” will always evaluate to be True; the same effect could be achieved by saying while 1==1: or while 2>1:.

Using the PRIMM approach

Before you go back to your rock, paper, scissors game, explore the concepts further using the PRIMM approach.

Predict

Ask students to look at the code below and predict what they think it will do:

1. answer = input("Is computer science your favourite subject? [Y/N] ")
2. agree = answer == "Y"
3.
4. while not agree:
5.  print("wrong answer")
6.  answer = input("Is computer science your favourite subject? [Y/N] ")
7.  agree = answer == "Y"
8.
9. print("You're right; computer science is the best")

Run

Did it work as you predicted? If not, what happened that was different to your prediction?

Students may want to think carefully about the statement agree = answer == "Y". First the logical statement answer == "Y" is evaluated, and the result of this is assigned to the agree variable.

Investigate

Ask students to work out the answers to the following questions by examining the code and running it a few times.

  • Run the code and enter in “Y”. What is printed on screen?
  • Run the code and enter in “N”. What is printed on screen?
  • What happens when you enter in “y” instead of “Y”? Why do you think this happens?

Work out the answers to the following questions by modifying the code as instructed and documenting how the changes have affected the program.

On line 3, add the following print statement:

print(agree)

Again, ask students to run the program a couple of times, entering in Y and then N. What does it print each time?

  • How does the value held in the agree variable affect what happens on line 4?
  • Remove the word not from line 4. Run your code a few times. What happens? Once you have done this, put the word not back into the code.

On lines 2 and 7, change the lines of code so that they look like the following:

agree = answer.upper() == "Y"

Now run your program again and test it using “y” and “Y”.

What do you think .upper() does?

Modify

Ask students to incorporate a while loop into their rock, paper, scissors game so that it keeps playing until the user decides to stop.

They can use the example code above to help them solve this problem.

You can download a copy of these PRIMM steps as a worksheet to use with your class here.

Further exploration of using rounds in the game

The aim in this step is to separate the functionality of the game into different functions, as well as using a different type of loop (a for loop) to control how many rounds of the game will be played.

The round function

Separating the functionality of the game allows us to achieve a level of modularity. Currently your program has a game() function that plays a round of your game.

You also have code outside of game() that runs this function. It makes sense to have two separate function: one for the round and one for the game. As more functionality is added to the game, it gets more complex, but by making each round independent of the running of the game in the long term you can reduce this complexity.

Creating these separate function comes with other advantages, too, such as making the code easier to read as well as easier to debug if anything goes wrong.

As you already have the code to run a round, but it is called game(), simply change the name of the function from game() to round():

Count-controlled loops

We’re now going to change how the game plays. Instead of asking the user if they want to play another round, we’re going to make the game play a set number of times.

Before you start, remove the following lines of code from your program:

answer = input("Do you want to play the game? [Y/N] ")
play = answer.upper() == "Y"

while play:
    game()
    answer = input("Do you want to play the game? [Y/N] ")
    play = answer.upper() == "Y"

Our code should now look like this:

from random import randint
 
rps_choices = ["Rock", "Paper", "Scissors"]

def round():
    
    print("Type 0 for Rock")
    print("Type 1 for Paper")
    print("Type 2 for Scissors")
    player = int(input("--> ")) # What happens if a user enters in a word/something that isn't an integer
    player_choice = rps_choices[player]
    computer_choice = rps_choices[randint(0,2)]

    print("You selected: "+player_choice)
    print("The computer selected: "+computer_choice)
        
    if player_choice == computer_choice:
        print("draw ")
        
    elif player_choice == "Rock" and computer_choice == "Scissors":
        print("You win :)")
            
    elif player_choice == "Paper" and computer_choice == "Rock":
        print("You win :)")
        
    elif player_choice == "Scissors" and computer_choice == "Rock":
        print("You Win :)")
        
    else:
        print("The computer wins :(")

print("Game over")

A count-controlled loop will iterate a set number of times; for this you will use a for loop. If you want your game to play five rounds, you need to call your round function five times.

Add the following lines of code at the end of the code outside of the round function:

def game():

   for i in range(5):
       round()
game()

Our full prgram should now look like this:

from random import randint
 
rps_choices = ["Rock", "Paper", "Scissors"]

def round():
    
    print("Type 0 for Rock")
    print("Type 1 for Paper")
    print("Type 2 for Scissors")
    player = int(input("--> ")) 
    player_choice = rps_choices[player]
    computer_choice = rps_choices[randint(0,2)]

    print("You selected: "+player_choice)
    print("The computer selected: "+computer_choice)
        
    if player_choice == computer_choice:
        print("draw ")
        
    elif player_choice == "Rock" and computer_choice == "Scissors":
        print("You win :)")
            
    elif player_choice == "Paper" and computer_choice == "Rock":
        print("You win :)")
        
    elif player_choice == "Scissors" and computer_choice == "Rock":
        print("You Win :)")
        
    else:
        print("The computer wins :(")
    
def game(): 
   for i in range(5):
       round()
       
game()       

We now have a system that has the main functionality in a separate function to the running of the game. It’s another good opportunity for you celebrate your achievement. Think about what would make this game better? Perhaps a score?

Adding a score

The functionality of our game would be improved by informing the user at the end whether or not they have won. To do this you need to find a way to include a score for the computer or the user when they win a round.

Start off by adding two variables: player_score and computer_score. Look at your code from the previous step and ask students where the best place for these variables would be. Also think about the initial values that these variables should hold.

The best place to initialise them is in the game() function. If you placed them in the round() function, what would happen in each round? You might have spotted that they would be set to their initial values each time a round is started, which would make it impossible to increment the score.

def game():

    player_score = 0
    computer_score = 0

    for i in range(5):
       round()

Returning values

We now need to find a way to tell our game() function who has won each round.

If you recorded only the winner in the round function, the winner of each round would be forgotten each time the function was called. The print() statements don’t help here: they display information to the user, not to other function.

To pass information from the round() function to the game() function you use the word return followed by a value. If the player wins, you should return “player” and if the computer wins you should return “computer". You don’t need to return anything if it is a draw, as it won’t have an impact on the score.

Update the if statements in the round() function so that it now includes return values:

if player_choice == computer_choice:
        print("draw ")

    elif player_choice == "rock" and computer_choice == "scissors":
        print("You win :)")
        return "player"

    elif player_choice == "paper" and computer_choice == "rock":
        print("You win :)")
        return "player"

    elif player_choice == "scissors" and computer_choice == "rock":
        print("You win :)")
        return "player"

    else:
        print("The computer wins :(")
        return "computer"

Using the return values

How are you going to use these return values? How do you use values that are being returned from other functions that you have come across? For example, would the following line of code do anything?

randint(0,3)

The answer is yes, it would. This line of code will return a value between 0 and 3, but you can’t do anything with that value, unless you either wrap it inside a print statement or use a variable to hold the return value. For example:

print(randint(0,3))

# or

number = randint(0,3)

As your round() function returns a value, you’ll need a variable to hold the value that it returns. Add a variable named winner that will hold the return value. In the game() function, change the line where you call round() to the following:

winner = round()
print(winner)

The variable winner will run round() as well as holding the value being returned. It’s often a good idea to add print statements such as the one above, to check what value the variable holding, and that it meets your expectations.

Finally, you need to check the return value and increment the appropriate score variables that you initialised earlier. Add the following lines of code under your winner variable:

if winner == "player":
  player_score +=1
elif winner == "computer":
  computer_score +=1

Now you can finish this step by printing to the screen:

  • The computer’s score
  • The player’s score
  • Where should the following two lines of code should be placed within your code?
print("The computer scored "+str(computer_score))
print("You scored "+str(player_score))

Our full prgram should now look like this:

from random import randint
 
rps_choices = ["Rock","Paper","Scissors"]

def round():
    
    print("Type 0 for Rock")
    print("Type 1 for Paper")
    print("Type 2 for Scissors")
    player = int(input("--> ")) 
    player_choice = rps_choices[player]
    random_choice = randint(0,2)
    computer_choice = rps_choices[random_choice]

    print("You selected: "+player_choice)
    print("The computer selected: "+computer_choice)
        
    if player_choice == computer_choice:
        print("draw ")
        
    elif player_choice == "Rock" and computer_choice == "Scissors":
        print("You win :)")
        return "player"
            
    elif player_choice == "Paper" and computer_choice == "Rock":
        print("You win :)")
        return "player"
        
    elif player_choice == "Scissors" and computer_choice == "Rock":
        print("You Win :)")
        return "player"
        
    else:
        print("The computer wins :(")
        return "computer"

def game():
    
    player_score = 0
    computer_score = 0
   
    for i in range(5):
       winner = round()
       #print(winner) 
       
       if winner == "player":
           player_score +=1
           
       elif winner == "computer":
           computer_score +=1 
       
    print("The computer scored: "+str(computer_score))
    print("You scored: "+str(player_score))

game() 

Testing

You’ve built the basis of a perfect rock, paper, scissors game. Before you get too carried away and think about releasing this to the public, you should take the important step of testing that it all works.

You should test your code regularly as you are developing it in order to catch any basic logic or syntax errors. This is known as developmental testing and doesn’t need to be formally recorded or documented. You’ll also need to get your students into the habit of doing this.

The complete program also needs testing, and this will occur near the end of your programming process; however, much of the preparation was done way back at the beginning when you were planning your solution. When you completed the unplugged step you were asked to think about how the game works, i.e. if you pick “rock” and the computer picks “scissors”, you will win the round. By identifying all the possible combinations and their intended outcomes, you’ve actually outlined a set of scenarios to test.

Run your program through enough times so that each scenario has been tested.

Player 1 Player 2 wins
1 Rock Paper Player 2 wins
2 Rock Scissors Player 1 wins
3 Paper Rock Player 1 wins
4 Paper Scissors Player 2 wins
5 Scissors Rock Player 2 wins
6 Scissors Paper Player 1 wins
7 Rock Rock Draw
8 Paper Paper Draw
9 Scissors Scissors Draw

Testing user input

One area of your program that should never be overlooked when testing is any part that involves user input (known as white-box testing).

Although you can guide, prompt, and cajole your user, you can never fully predict how they might act. Luckily, in your program there is only one place where the user enters data. Now you can test this fully and improve the robustness of your code. You can identify inputs or conditions for your program and the desired behaviours in each case; this is known as test data and can be categorised in three ways:

Test Description
Normal This is testing with data that you would expect the user to enter into the system and that you expect to work.
Boundary Sometimes known as extreme data, this is data that pushes the boundaries of normal data. Some boundary tests would be expected to pass, as the data falls inside the boundary of what you expect the system to accept, whereas you might deliberately complete a boundary test that is expected to fail as it falls just outside of what is normal data.
Erroneous This is testing using data that falls outside what is acceptable and should be rejected by the system.

Defensive Programming

You’ve managed to identify several errors by testing, but it would be helpful if you could catch these errors (called exceptions) and handle them without halting your program.

At the very least, you could display a more meaningful error message. This is known as defensive programming, and is a method of trapping exceptions and allowing your program to continue working without crashing. This step may be beyond the scope of Key Stage 3, but it is a useful technique to have available to stretch more able learners.

Analysing the errors

Start by seeing if you can reproduce some of the exceptions by entering invalid data into your program.

When you receive an error message, it’s important to note the type of error, as you can make your program respond differently to each. For example, the following inputs produce two different errors: an “IndexError” and a “ValueError”.

Input data Error
5 IndexError: list index out of range
abc ValueError: invalid literal for int() with base 10

Exception handling

You can handle these exceptions by preceding some “risky” code with a try statement:

try:
    player = int(input("--> "))

except:
    print("Oops, the computer didn’t like that input")

The code above will “try” to run the line player = int(input("--> ")). If any exception occurs, rather than throwing up a message and stopping the code from running, the code underneath the except statement will run instead.

Using exception handling, you can be a bit more specific about your exceptions and give different messages to the user depending on what error has occurred, by including the error type after the word except.

It would be more useful to handle your two types of error separately, as the feedback you give to the user might be different in each case.

For example, if they enter text, you can tell then to enter a number; if they enter a value that is a number but isn’t within the range, you can remind them what the range is.

Adding exception handling to your rock, paper, scissors game

You’re now going to create a new function that will handle the user input separately to your round() function. Again, this will make our code easier to read and debug.

Start by creating a new function above your round() function:

def player_input():

Your intention here is to catch the error and not allow the user to continue unless they put in valid input. You’ll add a while loop into your new function and start by placing the print statements from your round() function into your player_input() function:

def player_input():

    while True:

        print("Type 0 for rock")
        print("Type 1 for paper")
        print("Type 2 for scissors")

The next step is to add your try statement underneath these print statements.

        try:
            player = int(input("--> "))
            player_choice = rps_choices[player]
            return player_choice

Notice that again you have taken two more lines of code from your round() function, but you have added a line that returns a value. This will therefore now try to execute the three lines of code beneath it.

The first line of code in your round() function should now look as follows:

player_choice = player_input()

You might have noticed that we have two variables named player_choice that exist in your round() and player_input() function. As they exist in their own function, they don’t affect each other. You may want to rename one of them to avoid confusion.

Except

Finally, you need to go back to your player_input() function and add your except blocks. You have two possible exceptions to handle: a ValueError and an IndexError. You can handle these errors separately by writing two different except statements, each time including the type of error after except. As usual, indent your code to show it belongs to the except statement above it.

Add two separate except blocks under your try statement and customise the error messages to explain how to avoid that type of error.

Your player_input() function should now look like this:

def player_input():

    while True:

        print("Type 0 for rock")
        print("Type 1 for paper")
        print("Type 2 for scissors")

        try:
            player = int(input("--> "))
            player_choice = rps_choices[player]
            return player_choice

        except ValueError:
            print("Oops, looks like you entered text instead of a number. Please enter a whole number between 0 and 2")

        except IndexError:
            print("Oops, looks like you entered an incorrect number that wasn't a whole number between 0 and 2")

As you saw earlier in this step, it is also possible to simply use the word except and not be specific about the error, as follows. It can be good to use this to catch any errors that you haven’t thought of.

except:
  print("An error occurred")

This doesn’t necessarily help the user understand what they did wrong, but it does stop your program from crashing if an unexpected error occurs.

You can read more about exceptions in the Python documentation.

Our full prgram should now look like this:

from random import randint

rps_choices = ["Rock","Paper","Scissors"]

def player_input():
    
    while True:
        
        print("Type 0 for Rock")
        print("Type 1 for Paper")
        print("Type 2 for Scissors")
        
        try:
            player = int(input("--> ")) 
            player_choice = rps_choices[player]
            return player_choice
            
        except ValueError:
            print("Oops, looks like you entered text instead of a number. Please enter a number between 0-2")
            
        except IndexError:
            print("Oops looks like you entered a number that wasn't between 0-2")

def round():

    player_choice = player_input()

    computer_choice = rps_choices[randint(0,2)]

    print("You selected: "+player_choice)
    print("The computer selected: "+computer_choice)

    if player_choice == computer_choice:
        print("draw ")
        
    elif player_choice == "Rock" and computer_choice == "Scissors":
        print("You win :)")
        return "player"
            
    elif player_choice == "Paper" and computer_choice == "Rock":
        print("You win :)")
        return "player"
        
    elif player_choice == "Scissors" and computer_choice == "Rock":
        print("You Win :)")
        return "player"
        
    else:
        print("The computer wins :(")
        return "computer"


def game():
    
    player_score = 0
    computer_score = 0
   
    for i in range(5):
       winner = round()
       
       
       if winner == "player":
           player_score +=1
       elif winner == "computer":
           computer_score +=1
       
    print("The computer scored: "+str(computer_score))
    print("You scored: "+str(player_score))

game()  

Pair Programming Exercise

Using what we've learned by building a rock, paper, scissors game your task is to create a ticket machine program

The ticket machine

Develop a program for a ticket machine where you can purchase a ticket for a theme park. The user should be able to select:

  • An adult ticket (£10)
  • A child ticket (£6)
  • A family ticket (£20)

The machine will only allow the user to enter values of £1, £2, or £5. Once the ticket price has been reached or exceeded, the machine will work out and return (print to screen) the correct change if the user has exceeded the ticket price.

@aminiarshia

Copy link
Copy Markdown

Thank you very much. I learned a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment