Get started in programming with Python: Rock-paper-scissors code along

Yung Han Jeong
6 min readOct 26, 2020

“Could you recommend a simple coding projects for my sophomore students?”, my friend asked. “Rock-paper-scissors…?”, I answered with fleeting confidence as I barely grasped the scope of said project. The horrors of input validation back in my college C++ course came back and started to haunt me. I quickly realized that this program might be beyond the scope of a complete novice.

Fortunately, with the guide of my friend we were able condense the code to fit the curriculum of young students. It has it’s obvious flaws, but it’s simple enough for novice to complete within few hours while practicing some basic ideas like if statements and built in functions. You can check out the code below.

This also got me started on a rabbit hole of completing this project to my satisfaction and inspired me to create this code along. I will assume that you have completed basics of coding/python and if you are not familiar, I highly suggest checking out this free tutorial on Kaggle first.

image source: UFC, Sean O’Connell Vs Anthony Perosh

Let’s start with some pseudocode to outline the project.

1. The program will prompt the users for input (rock, paper, scissors).
1A. The program will check for valid input. If the input is not
valid, it will "yell" at the user and ask for proper input
until a valid response is provided.
2. The computer will choose randomly between rock, paper, and scissors.3. The program will compare and announce the result.4. The program will ask if the user wants to play again and if player selects yes it will repeat the game.

Player Input

Prompting the user for input is done with built in input() function and that can be stored in a variable like so:

player_input = input() #whatever the user types will be stored here

The tricky bit here is checking for a proper input. An invalid input will create logic issues and our code won’t work properly. Since the user choice in this game is very limited we can create a list of that contain proper input and check the user input against the list. This can be accomplished with “in” operator in Python.

"rock" in ["rock", "paper", "scissors"] #this returns "True"

However, we should also account for varying capitalization from user input like “Rock” or “rock”. Rather than growing the valid input list we can process the input further for more controlled comparison. I think that chaining .lower() method would be the easiest way to proceed.

player_input = input().lower() #if player input is "rOcK"
print(player_input) # the print out will be "rock"

Now that we have a clean player input and a way to validate the input, let’s create the actual logic that checks for the valid input. If the user input is invalid, the computer should keep asking for a valid input until a valid one is provided. A while loop can be used for this continuous process like below.

choices = ["rock", "paper", "scissors"] #possible choices
player_input = input().lower() #ask for input
while player_input not in choices: #while the input is not valid
print("That is not a valid input!") #yell at user
player_input = input().lower() #ask for the input again

Now that the logic is completed, we should wrap it in a function for easier usage in the future. I also added some print statements to make the function more “game-like”. Please note that I have elected to use the “choices” list as a global variable. This list will be used again in the future for the computer’s selection.

choices = ["rock", "paper", "scissors"] #valid input#asks user for input until it's valid
#return the input
def player_input_check():
player_input = input("Rock, Paper, or Scissors? ").lower()
while player_input not in choices: #while input not valid
print("That is not a valid input!") #yell at user
player_input = input("Rock, Paper, or Scissors? ").lower()
return player_input

Boom! The first part of the project and perhaps the most difficult part of the project is complete.

image source: The Emperor’s New Groove

Computer’s Choice

To play against the computer, the computer needs to make it’s choice. There are few options to choose make computer choose “randomly”, but we will use the random Python library and use the .choice() method.

import random #import random librarychoices = ["rock", "paper", "scissors"] #valid input/choicescomputer_choice = random.choice(choices) #pick random from list
print("Computer's choice: ", computer_choice) #print computer choice
image source: Team Fortress 2 Meet The Spy

Who won?

There are total seven outcomes in a game of rock-paper-scissors: 6 victory conditions and 1 draw (technically 3 draws, but only 1 comparison is required). Since, there are only few statements to check against we will use if else (elif) statements for victory conditions.

image source: wikipedia.org

To build the function let’s first call the function we just made and save it to a local variable. Then, we will add the logic for computer’s choice in the game. Last, we can build the series of if/elif statement to calculate who won the match. We can also add 2 additional variables to keep track of the score and every time the player or computer wins their score will go up by 1. The function will return their resulting scores for later use.

import randomchoices = ["rock", "paper", "scissors"] #valid input/choices
player_score = 0
computer_score = 0
# receives player input and scores
# makes computer choice
# compare and print result. Calculate and return scores.
def who_won(p_score, c_score):
p_choice = player_input_check()#get player input
print("Your choice: ", p_choice.title()) #print out input
computer_choice = random.choice(choices)
print("Computer's choice: ", computer_choice.title())
#logic comparison
if computer_choice == p_choice: #draw condition
print("It's a draw!")
elif computer_choice == "rock" and p_choice == "paper":
print("You win!")
p_score += 1
elif computer_choice == "rock" and p_choice == "scissors":
print("Computer wins!")
c_score += 1
elif computer_choice == "paper" and p_choice == "scissors":
print("You win!")
p_score += 1
elif computer_choice == "paper" and p_choice == "rock":
print("Computer wins!")
c_score += 1
elif computer_choice == "scissors" and p_choice == "paper":
print("Computer wins!")
c_score += 1
elif computer_choice == "scissors" and p_choice == "rock":
print("You win!")
p_score += 1

return p_score, c_score

Check for rematch!

Now all there is left is to call our functions and wrap them in while loop similar to player_input_check function. We can also display the scores with outputs from the output of who_won function. In the example below I used fstring to print the results, but you can also use .format() method.

#variable initialization
choices = ["rock", "paper", "scissors"] #valid input/choices
play_again_yes = ["yes","y"] #same idea as list above
player_score = 0 #initialize scores
computer_score = 0
play_again = play_again_yes[0]
#Functions we wrote so far up here, redacted for formatting. while play_again in play_again_yes: #if the choice is a yes or y
#run the game and get scores
player_score, computer_score = who_won(player_score, computer_score)
#print result
print("\n") #white space for formatting
print(f"Current Score is Player: {player_score} Computer: {computer_score}")
print("Play Again? (Y/N)")
#check for playing again
play_again = input().lower()
print("\n") #white space for formatting

Now you can run your program and test it! You can run from your IDE or save and call it from your command/command prompt. I ran mine on command prompt and below is a screenshot of the result. I decided that I’ve played enough after two consecutive losses.

My game against the computer. Womp womp…

There are additional improvements you can make here as well, but I think this is a solid project for a beginner to complete. You can check out below for the complete code and you can find a more detailed code along on my github repo. I hope you learned something new with this code along!

Bonus Challenge: Take advantage of object oriented programming for organization. Create a class for this game, initialize necessary variables in __init__, and store all functions under the class. Then, create a game file that uses the new class. You can find this implementation on my github repo as well.

--

--