import random def input_stripped(prompt): """ Same as input(), but strips whitespace and converts to lower case. """ return input(prompt).strip().lower() def get_user_move(): """ Asks the user for one of 'rock', 'paper', or 'scissors' until they enter a valid choice, then returns the number associated with that choice. """ choice = input_stripped('Rock, paper, or scissors? ') while choice not in {'rock', 'paper', 'scissors'}: choice = input_stripped("Please enter one of 'rock', 'paper', or 'scissors': ") return choice def get_computer_move(): """ Return a random number representing a choice. """ return random.choice(['rock', 'paper', 'scissors']) def get_winner(a, b): """ Returns 'tie', 'left', or 'right' according to which of the moves a, b wins. """ if a == b: return 'tie' # If you order the choices as rock, paper, scissors and imagine that the # list wraps back around to rock after scissors, then element i+1 always beats # element i. The following test implements this idea. nums = {'rock': 0, 'paper': 1, 'scissors': 2} if (nums[a] + 1) % 3 == nums[b]: return 'right' return 'left' def get_number_of_rounds(): """ Ask the user for a number of rounds to play until they enter a valid positive integer. """ while True: try: num = int(input_stripped('How many rounds would you like to play? ')) if num <= 0: print('Please enter a positive number') else: return num except ValueError: print('Please enter a valid number') def do_game(): """ Asks the user for a number of rounds, plays that many rounds, and outputs a final score at the end. """ rounds = get_number_of_rounds() win_count = 0 for round in range(rounds): print('Round {0}: your score is {1}'.format(round + 1, win_count)) comp_move = get_computer_move() user_move = get_user_move() print('The computer chose {0}'.format(comp_move)) winner = get_winner(user_move, comp_move) if winner == 'tie': print("It's a tie!") elif winner == 'left': print('You win!') win_count += 1 else: print('The computer wins :(') print('You won {0} of {1} rounds!'.format(win_count, rounds)) do_game()
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