Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Random Fun and Games: Go Ahead, Take a Chance! 117

RockPaperScissors.py

u import random
v choices = ["rock", "paper", "scissors"]
print("Rock crushes scissors. Scissors cut paper. Paper covers rock.")
w player = input("Do you want to be rock, paper, or scissors (or quit)? ")
x while player != "quit": # Keep playing until the user quits
player = player.lower() # Change user entry to lowercase
y computer = random.choice(choices) # Pick one of the items in choices
print("You chose " +player+ ", and the computer chose " +computer+ ".")
z if player == computer:
print("It's a tie!")
{ elif player == "rock":
if computer == "scissors":
print("You win!")
else:
print("Computer wins!")
| elif player == "paper":
if computer == "rock":
print("You win!")
else:
print("Computer wins!")
} elif player == "scissors":
if computer == "paper":
print("You win!")
else:
print("Computer wins!")
else:
print("I think there was some sort of error...")
print() # Skip a line
~ player = input("Do you want to be rock, paper, or scissors (or quit)? ")


At u, we import the random module to get access to the func-
tions that help us make random choices. At v, we set up the list
of the three items—rock, paper, and scissors—and call the list
choices. We print the simple rules of the game to make sure the
user knows them. At w, we prompt the user to input their choice
of rock, paper, scissors, or quit and store their choice in the variable
player. At x, we begin the game loop by checking whether the user
chose quit at the input prompt; if they did, the game ends.
As long as the user has not entered quit, the game begins. After
changing the player’s input to lowercase for easy comparison in our
if statements, we tell the computer to pick an item. At y, we tell the
computer to pick at random one of the items in the list choices and
store the item in the variable computer. Once the computer’s choice
is stored, it’s time to begin testing to see who won. At z, we check
Free download pdf