Python Functions - Rock Paper Scissors game

wordcloud

This is an illustration of basics of Python functions. In this example, we will write a simple Rock-Paper-Scissors using Python functions.

Here is an example of defining a simple function that prints something and how to call the function.

In [1]:
# Define print_hand function
def print_hand():
    print('You picked: Rock')
# Call print_hand function
print_hand()
You picked: Rock

The function above takes no arguments. Let's pass an argument called hand and print it.

In [2]:
# Add a parameter to print_hand
def print_hand(hand):
    # Use the parameter to print 'You picked: ___'
    print('You picked: '+hand)

# Call print_hand with 'Rock'
print_hand('Rock')

# Call print_hand with 'Paper'
print_hand('Paper')
You picked: Rock
You picked: Paper

Now let's pass multiple arguments. While passing more than one argument, the sequence or order of arguments must match with the function definition.

In [3]:
# Add a parameter to print_hand
def print_hand(hand,name):
    # Change the output to '___ picked: ___'
    print(name+' picked: ' + hand)

# Add a second argument to print_hand
print_hand('Rock','Player')

# Add a second argument to print_hand
print_hand('Paper','Computer')
Player picked: Rock
Computer picked: Paper

We can also make some arguments optional be providing them with default values.

In [4]:
# Add a default value for name
def print_hand(hand, name='Guest'):
    print(name + ' picked: ' + hand)

# Add an argument to print_hand
print_hand('Rock')
Guest picked: Rock

Default argument values will be overwritten when their values are passed to the function. Let's input player's name.

In [5]:
# Get input, and then assign it to the player_name variable
player_name=input('Please enter your name: ')
# Add a second argument to print_hand
print_hand('Rock',player_name)
Krishnakanth picked: Rock

Let's add an option to select hand.

In [6]:
def print_hand(hand, name='Guest'):
    # Assign a list of hands to the hands variable
    hands=['Rock','Paper','Scissors']
    
    # Update using an element of the hands variable
    print(name + ' picked: ' + hands[hand])

print('Starting the Rock Paper Scissors game!')
player_name = input('Please enter your name: ')
# Print 'Pick a hand: (0: Rock, 1: Paper, 2: Scissors)'
print('Pick a hand: (0: Rock, 1: Paper, 2: Scissors)')

# Get input, convert it, and assign it to the player_hand variable
player_hand=int(input('Please enter a number (0-2): '))

# Change the first argument to player_hand
print_hand(player_hand, player_name)
Starting the Rock Paper Scissors game!
Pick a hand: (0: Rock, 1: Paper, 2: Scissors)
Krishnakanth picked: Scissors

We need to ensure that the player only selects 0, 1 or 2 and nothing else. Let's add another function to validate player input using an if...else statement.

In [10]:
# Define the validate function
def validate(hand):
    # Add control flow based on the value hand
    if hand<0 or hand>2:
        return False
    else:
        return True
    
def print_hand(hand, name='Guest'):
    hands = ['Rock', 'Paper', 'Scissors']
    print(name + ' picked: ' + hands[hand])

print('Starting the Rock Paper Scissors game!')
player_name = input('Please enter your name: ')

print('Pick a hand: (0: Rock, 1: Paper, 2: Scissors)')
player_hand = int(input('Please enter a number (0-2): '))

# Add control flow based on the return value of the validate function
if validate(player_hand):
    print_hand(player_hand, player_name)
else:
    print('Please enter a valid number')
Starting the Rock Paper Scissors game!
Pick a hand: (0: Rock, 1: Paper, 2: Scissors)
Krishnakanth picked: Rock

Is there a simpler way to write the validate function? Let's try.

In [11]:
# Define the validate function
def validate(hand):
    return 0<=hand<=2

Now that the player is able to select a hand, let's assign a hand to the computer too. Let's begin with the computer always selects 'Paper'.

In [12]:
if validate(player_hand):
    # Assign 1 to the computer_hand variable
    computer_hand=1
    
    print_hand(player_hand, player_name)
    # Call print_hand function with computer_hand and 'Computer' as arguments
    print_hand(computer_hand,'Computer')
    
else:
    print('Please enter a valid number')
Krishnakanth picked: Rock
Computer picked: Paper

Now we'll create another function Judge to determine the winner using if-else statements.

In [13]:
# Define the judge function
def judge(player,computer):
    # Add control flow based on the comparison of player and computer
    if player==computer:
        return 'Draw'
    elif player==0 and computer==1:
        return 'Lose'
    elif player==1 and computer==2:
        return 'Lose'
    elif player==2 and computer==0:
        return 'Lose'
    else:
        return 'Win'

if validate(player_hand):
    computer_hand = 1
    
    print_hand(player_hand, player_name)
    print_hand(computer_hand, 'Computer')
    
    # Assign the return value of judge to the result variable
    result=judge(player_hand,computer_hand)
    # Print the result variable
    print('Result: '+result)
else:
    print('Please enter a valid number')
Krishnakanth picked: Rock
Computer picked: Paper
Result: Lose

Is there a simpler way to write the Judge function here?

In [14]:
# Define the judge function
def judge(player,computer):
    # Add control flow based on the comparison of player and computer
    if player-computer in [1,-2]:
        return 'Win'
    elif player==computer:
        return 'Draw'
    return 'Lose'

if validate(player_hand):
    computer_hand = 1
    
    print_hand(player_hand, player_name)
    print_hand(computer_hand, 'Computer')
    
    # Assign the return value of judge to the result variable
    result=judge(player_hand,computer_hand)
    # Print the result variable
    print('Result: '+result)
else:
    print('Please enter a valid number')
Krishnakanth picked: Rock
Computer picked: Paper
Result: Lose

We would like the computer to select a hand randomly using the random function. Here is the complete code for the rock-paper-scissors game.

In [15]:
def print_hand(hand, name='Guest'):
    hands = ['Rock', 'Paper', 'Scissors']
    print(name + ' picked: ' + hands[hand])
    
def validate(hand):
    return 0<=hand<=2

def judge(player,computer):
    if player-computer in [1,-2]:
        return 'Win'
    elif player==computer:
        return 'Draw'
    return 'Lose'

# import the random module
import random

print('Starting the Rock Paper Scissors game!')
player_name = input('Please enter your name: ')

print('Pick a hand: (0: Rock, 1: Paper, 2: Scissors)')
player_hand = int(input('Please enter a number (0-2): '))

if validate(player_hand):
    # Assign a random number between 0 and 2 to computer_hand using randint
    computer_hand = random.randint(0,2)
    print_hand(player_hand, player_name)
    print_hand(computer_hand, 'Computer')
    result = judge(player_hand, computer_hand)
    print('Result: ' + result)
else:
    print('Please enter a valid number')
Starting the Rock Paper Scissors game!
Pick a hand: (0: Rock, 1: Paper, 2: Scissors)
Krishnakanth picked: Paper
Computer picked: Rock
Result: Win

Note: The code on this page is something that I wrote when I took Progate's free Python classes.

Last updated 2020-12-01 15:56:41.395022 IST

Comments