[Tutor] Paper Rock Scissors game - User's choice not returned properly

Wayne Werner waynejwerner at gmail.com
Mon Oct 31 20:07:22 CET 2011

On Mon, Oct 31, 2011 at 1:14 PM, Marc Tompkins <marc.tompkins at gmail.com>wrote:

> You could simplify it even further by actually using the "while":
> > def UserChoice ():    # The function that returns the choice from the
> user
> >    choice = ''
> >    attempt = 0
> >    while choice.lower() not in ('p', 'r','s'):
> >        if attempt > 0: print 'Please try again.'
> >        print 'Please select (P) for paper, (R) for Rock, or (S) for
> Scissors.'
> >        choice = raw_input('What is your selection?: ')
> >        attempt +=1
> >    return choice.lower()
> It's a matter of personal preference, but I try to avoid "while 1" or
> "while True" loops if at all possible.  For one thing, it seems
> counter-productive to set up a loop that doesn't exit, and then to
> have to use 'break' to get out of it!

As a slight aside, I came up with a (fairly) simple recipe for this sort of

def prompt(choices):
        for choice, desc in choices:
            print("%2s. %s" % (choice, desc))
        prompt.choice = input("Choice: ") #use raw_input in Python 2.x
        return prompt.choice
    except TypeError:
        raise ValueError("prompt expects collection of pairs")

Then you can do something like this:

while prompt([("P", "Paper"), ("R", "Rock"), ("S", "Scissors)]).lower() not
in ('p', 'r', 's'):
    print("Error: ", prompt.choice, " is not a valid choice!")

#do something with prompt.choice here

It handles keeping track of whatever the last choice was for you, and all
you have to do is pass it a collection of pairs. If you wanted to make it
specifically for your application, you could just change it to this:

def prompt():
   print("or (S)cissors?")
   prompt.choice = raw_input("Choice: ")
   return prompt.choice

while prompt().lower() not in ('p', 'r', 's'):
   #print error message

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111031/a67c1042/attachment.html>

More information about the Tutor mailing list