# This program uses fstrings, which is a feature exclusive to newer versions of Python import random valid_choices = {'rock', 'paper', 'scissors'} numbering = {'rock': 0, 'paper': 1, 'scissors': 2} names = {0: 'rock', 1: 'paper', 2: 'scissors'} min_number, max_number = 0, 2 def get_number_of_rounds(): while True: num_str = input("How many rounds would you like to play? ") try: num = int(num_str) if num <= 0: print("You need to play at least one round!") else: return num except ValueError: print("That is not a valid number!") def get_user_choice(): # Prompts the user for input until valid choice is made. Return corresponding choice number choice = input("Rock, paper, or scissors? ").lower().strip() while choice not in valid_choices: choice = input("Please enter one of the following: 'rock', 'paper', or 'scissors': ") return numbering[choice] def get_computer_choice(): # Randomly generated choice by computer return random.randint(min_number, max_number) def get_winner(l, r): # Returns -1 if l beats r, 0 if there is a tie, and 1 if r beats l if l == r: return 0 if (l + 1) % (max_number + 1) == r: return 1 return -1 def play_round(): # Plays a round: user makes choice, computer makes choice, returns true if player wins, false otherwise user_choice = get_user_choice() computer_choice = get_computer_choice() print(f"The computer chose {names[computer_choice]}") winner = get_winner(user_choice, computer_choice) if winner == -1: print("You won!") elif winner == 0: print("There was a tie!") else: print("The computer won.") return winner == -1 def play_game(): num_rounds = get_number_of_rounds() num_won = 0 for i in range(num_rounds): player_won = play_round() if player_won: num_won += 1 rounds_plural = "s" if num_rounds > 1 else '' print(f"You won {num_won} out of {num_rounds} round{rounds_plural}!") if __name__ == '__main__': play_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