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.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Step 1: write winner(player, computer) that retornos "player", "computer" or "draw". Rock beats scissors, scissors beats paper, and paper beats rock.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Step 2: write message(player, computer) that retornos "You win!", "Computer wins!" or "Draw!". Call your winner function inside it instead of repeating the rules.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Step 3: players make typing mistakes. Write is_valid(move) that retornos True for rock, paper or scissors, in any capitals and with spaces around it, and False for anything else.
Haz clic en Ejecutar para ver la salida aquí.