<div class="gmail_quote">On Mon, Oct 31, 2011 at 1:14 PM, Marc Tompkins <span dir="ltr"><<a href="mailto:marc.tompkins@gmail.com">marc.tompkins@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div class="im"><br>
</div>You could simplify it even further by actually using the "while":<br>
<div class="im"><br>
> def UserChoice (): # The function that returns the choice from the user<br>
</div>> choice = ''<br>
> attempt = 0<br>
> while choice.lower() not in ('p', 'r','s'):<br>
> if attempt > 0: print 'Please try again.'<br>
<div class="im">> print 'Please select (P) for paper, (R) for Rock, or (S) for Scissors.'<br>
> choice = raw_input('What is your selection?: ')<br>
</div>> attempt +=1<br>
> return choice.lower()<br>
<br>
It's a matter of personal preference, but I try to avoid "while 1" or<br>
"while True" loops if at all possible. For one thing, it seems<br>
counter-productive to set up a loop that doesn't exit, and then to<br>
have to use 'break' to get out of it!<br></blockquote><div><br></div><div>As a slight aside, I came up with a (fairly) simple recipe for this sort of occasion:</div><div><br></div><div>def prompt(choices):</div><div>
try:</div><div> for choice, desc in choices:</div><div> print("%2s. %s" % (choice, desc))</div><div> prompt.choice = input("Choice: ") #use raw_input in Python 2.x</div><div>
print()</div><div> return prompt.choice</div><div> except TypeError:</div><div> raise ValueError("prompt expects collection of pairs")</div><div><br></div><div>Then you can do something like this:</div>
<div><br></div><div>while prompt([("P", "Paper"), ("R", "Rock"), ("S", "Scissors)]).lower() not in ('p', 'r', 's'):</div><div> print("Error: ", prompt.choice, " is not a valid choice!")</div>
<div><br></div><div>#do something with prompt.choice here</div><div><br></div><div>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:</div>
<div><br></div><div>def prompt():</div><div> print("(P)aper")</div><div> print("(R)ock")</div><div> print("or (S)cissors?")<br> prompt.choice = raw_input("Choice: ")</div><div>
return prompt.choice</div><div><br></div><div>while prompt().lower() not in ('p', 'r', 's'):</div><div> #print error message</div><div><br></div><div>HTH,</div><div>Wayne</div></div>