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

Marc Tompkins marc.tompkins at gmail.com
Mon Oct 31 19:14:21 CET 2011


On Mon, Oct 31, 2011 at 10:57 AM, Joel Montes de Oca
<joelmontes01 at gmail.com> wrote:
>
>  I came up with this to solve the problem.
>
> def UserChoice ():    # The function that returns the choice from the user
>     while 1:
>
>         print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'
>         choice = raw_input('What is your selection?: ')
>         if choice.lower() in ('p', 'r','s'):    # Converts the user's choice to lowercase and confirms the choice is valid
>             return choice
>             break
>         else:
>             print 'Try again.'
>
> It puts the choice into a loop and only exits when the user enters a valid value. It works and it's so much easier to read too!
>

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!

One last thing:  HTML formatting is pretty, but it tends to screw
things up.  Someone else is bound to say it if I don't, so:  please
use plain text only when submitting code to the list.  Thanks!


More information about the Tutor mailing list