Week 1, Problem 3: The
Road Not Taken: Choosing Code Paths
[20
points; individual]
This problem asks you to write a Python function that
test the use of the if
elif
and else
constructs in python. Be sure to test your function carefully. Also, be sure to
include a docstring under the signature line of the function. The docstring
should indicate what the function computes (outputs) and what its inputs are or
what they mean.
Please put your function for this problem in a single file named hw1pr3.py
. Please
name your function exactly as specified (including upper/lower case) -- it will
help keep the graders happy -- which is always a good thing!
(#1) Building from last week's
rock-paper-scissors game (which did not have to be fair), for this week, write
a function rps()
that plays a game of
rock-paper-scissors fairly.
That is, it should first choose randomly from the three choices, though it
should not reveal that choice! Then, the function should ask the user for her
choice. Afterwards, it should print its original choice, the user's choice, and
then declare the winner.
In addition, your rps function should print a
warning if the user does not input one of 'rock'
, 'paper'
,
or 'scissors'
.
Choosing
items at random from a sequence
To generate a random element from a list, model your
code from the following example:
from random import *
s = choice( [ 'thread', 'yarn', 'twine' ])
print('I chose', s)
The above code will print a potentially different
string each time it is run.
Print
vs. return
Note that rps()
takes no inputs and it has no return
value -- it's a function that interacts with the user only via print
and input
statements. Thus, rps
does not need to return anything. It is a good example of a
function in which print
is the desired means of interaction.
Playing
again with while
Optionally, your function could use a while
loop, in which it asks the user to play again and then continue (or not), based
on their answer. This is not required, but if you'd like to do so, the
following example shows how a while loop works:
answer = 'no'
while answer == 'no':
[body of the program]
answer = input('Would you like to stop?
')
Examples
Here are two separate example runs with the user's
input in blue -- feel free to adjust the dialog for the sake of yourself (or
the graders):
>>> rps( )
Welcome to RPS! I
have made my choice.
Choose your poison:
scissors
You chose scissors.
I chose rock.
I win!
And I didn't even
cheat this time!
>>> rps( )
Welcome to RPS! I
have made my choice.
Choose your poison:
paper
You chose paper.
I chose rock.
You win!
I may have to
reconsider my strategy in this game...
Submitting your file
You should submit your hw1pr3.py
file at Canvas.
Next
Continue working on homework 1: hw1pr4