Project: Rock, paper, scissors
Project: Rock, paper, scissors
- You play rock, paper, scissors against the computer.
- The rules live in functions that return an answer, so each part is easy to test.
- You use functions,
return,ifwithand/or, and string methods.
What you will build
rock, paper or scissors? Rock
The computer chose scissors.
You win!
Step 1: who wins?
- Same move: a draw.
- Rock beats scissors, scissors beats paper, paper beats rock.
- A function can
returnas soon as it knows the answer. The lines after thatreturndo not run.

Step 2: functions can use functions
messagedoes not repeat the rules. It callswinnerand turns the result into words.- One rule in one place: if the rules change, you change only
winner.
Step 3: check what the player typed
.strip()removes spaces at both ends;.lower()makes small letters.- A comparison like
move == "rock"is alreadyTrueorFalse, so you canreturnit directly.
Play for real
random.choice(list)picks one item at random: the computer's move. Run this and play in the input box.
import random
def winner(player, computer):
if player == computer:
return "draw"
if (player == "rock" and computer == "scissors") or (player == "scissors" and computer == "paper") or (player == "paper" and computer == "rock"):
return "player"
return "computer"
def message(player, computer):
result = winner(player, computer)
if result == "player":
return "You win!"
if result == "computer":
return "Computer wins!"
return "Draw!"
move = input("rock, paper or scissors? ").strip().lower()
computer = random.choice(["rock", "paper", "scissors"])
print("The computer chose " + computer + ".")
print(message(move, computer))
Now build it
- Three steps. Press Check answer after each one: the checks call your functions with many moves.
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Step 1: write winner(player, computer) that rendements "player", "computer" ou "draw". Rock beats scissors, scissors beats paper, and paper beats rock.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Step 2: write message(player, computer) that rendements "You win!", "Computer wins!" ou "Draw!". Call your winner function inside it instead of repeating the rules.
Cliquez sur Exécuter pour voir le résultat ici.
Difficulté 3/5 · 200 pièces + un petit bonus lors de la première réussite aujourd'hui
Step 3: players make typing mistakes. Write is_valid(move) that rendements True for rock, paper ou scissors, in any capitals and with spaces around it, and False for anything else.
Cliquez sur Exécuter pour voir le résultat ici.