Python: Rock Paper Scissors


#1

Why isn't my program exiting when it hits the break? I keep getting:

File "python", line 23
SyntaxError: 'break' outside loop

#Rock Paper Scissors Game
import random

#Ask user for their choice and check for invalid choice
choice = raw_input("Rock, Paper, or Scissors: ").upper()
if choice != "ROCK" or choice != "PAPER" or choice != "SCISSORS":
    print "Oops, Looks like that wasn't a valid choice. Are you sure you spelled it corectly?"
else:
    continue

#Create Computers choice
comp = random.randint(0,3)
if comp == 0:
    comp = "Rock"
elif comp == 1:
    comp = "Paper"
else:
    comp = "Scissors"
print "The computer picked " + comp + "."

#Compare users choice to computers choice to determine winner
if choice == comp.upper():
    print "It's a tie!"
elif choice == "ROCK":
    if comp == "Paper":
        print "The Computer Wins!"
    elif comp == "Scissors":
        print "You Win!!"
elif choice == "PAPER":
    if comp == "Scissors":
        print "The Computer Wins!"
    elif comp == "Rock":
        print "You Win!!"
else: #scissors
    if comp == "Rock":
        print "The Computer Win!"
    elif comp == "Paper":
        print "You Win!!"

#2

Where is your loop construct? We can only write break inside a loop.


#3

Hi, @ghughes13 ,

There's an additional problem with this logic ...

if choice != "ROCK" or choice != "PAPER" or choice != "SCISSORS":

If choice is "ROCK", what will happen?


#4

@mtf @appylpye Pasted the full code. So how would I write it so that it exits the program, or prompts the user to enter again, if the choice variable is something other than the 3 choices?


#5

Hi, @ghughes13 ,

As @mtf pointed out, you can only use break within a loop. The same is true of continue. You have it in an else block, but not inside a loop.

Here's some code for experimentation. While it is not the exact solution to this task, it is close enough for you to examine, and then to use as a model for part of an actual solution. Notice that is uses the and operator. Make sure you understand how this code works, including why we need and instead of or, before completing the solution for the game.

while True:
    choice = raw_input("X, Y, or Z: ").upper()
    if choice != "X" and choice != "Y" and choice != "Z":
        print "Oops, you made an invalid choice."
    else:
        break

print choice

Also note that this ...

comp = random.randint(0,3)

... assigns 0, 1, 2, or 3 to comp. Instead, you should only assign 0, 1, or 2 to comp.


#6