#Jannitta Yao #Girls Who Code Application import random def isValidGesture(gesture): """Returns True if gesture is one of the strings 'rock', 'paper', or 'scissors', and False otherwise.""" return gesture == 'rock' or gesture == 'paper' or gesture =='scissors' def randomGesture(): """Randomly returns one of 'rock', 'paper', or 'scissors', with equal probability.""" outcome = random.randint(1,3) if outcome == 1: return 'rock' elif outcome == 2: return 'paper' elif outcome == 3: return 'scissors' def beats(gesture1, gesture2): """Returns True if the first gesture beats the second gesture, i.e., if the first and second gesture are rock/scissors or scissors/paper, or paper/rock, respectively. Returns False otherwise. The output is unspecified if one or both gestures is invalid.""" win1 = gesture1 == 'rock' and gesture2 == 'scissors' win2 = gesture1 == 'scissors' and gesture2 == 'paper' win3 = gesture1 == 'paper' and gesture2 == 'rock' return win1 or win2 or win3 def play(you, opponent): """Plays rock/paper/scissors game with your gesture vs. opponent's gesture. If both gestures are valid, displays one of 'Game is a tie!', 'You win!', or 'Opponent wins!'. Otherwise, indicates the first gesture that is invalid.""" valid = isValidGesture(you) and isValidGesture(opponent) == True error1 = isValidGesture(you) == False error2 = isValidGesture(opponent) == False youWin = beats(you,opponent) == True other = beats(you, opponent) == False if valid and youWin: print 'You win!' elif valid and other and you != opponent: print 'Opponent wins!' elif valid and other and you == opponent: print 'Game is a tie!' if not valid and error1: print "Your gesture ({}) is invalid".format(you) elif not valid and error2: print "Opponent's gesture ({}) is invalid".format(opponent) def playComputer(you): """Plays rock/paper/scissors with your gesture against a computer opponent that randomly chooses a gesture. First displays the choice of the computer, and then displays the result of the game.""" computer = randomGesture() print 'Computer chooses', computer play(you, computer) #if __name__ == "__main__": """Uncomment lines below to run the play and playComputer functions.""" # play('rock', 'scissors') # play('rock', 'paper') # play('paper', 'paper') # playComputer('rock') # playComputer('scissors') # playComputer('paper') # playComputer('Leia')
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question