About the project:This project will allow you to play against the computer. You will choose Rock, Paper, or Scissors, the computer will make its own random choice, and then the game will determine and display the winner.
Allows the user to choose its own chice.
How to play:
- Run the Python script.
- The game will prompt you to choose Rock, Paper, or Scissors. Type your choice and press Enter.
- The computer will then make its choice, and the result of the round will be displayed.
- TAfter each round, you will be asked if you want to play again. Type yes to continue or no to quit.
Project Level: Beginner
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: choose any code snippet and follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# rock_paper_scissors.py
import random
def get_user_choice():
"""
Gets the user's choice (Rock, Paper, or Scissors) and validates it.
Returns the validated choice in lowercase.
"""
while True:
user_input = input("Choose Rock, Paper, or Scissors: ").strip().lower()
if user_input in ["rock", "paper", "scissors"]:
return user_input
else:
print("Invalid choice. Please enter 'Rock', 'Paper', or 'Scissors'.")
def get_computer_choice():
"""
Generates a random choice (Rock, Paper, or Scissors) for the computer.
Returns the computer's choice in lowercase.
"""
choices = ["rock", "paper", "scissors"]
return random.choice(choices)
def determine_winner(user_choice, computer_choice):
"""
Determines the winner of the Rock, Paper, Scissors game.
Returns a string indicating the result (Win, Lose, or Tie).
"""
print(f"\nYou chose: {user_choice.capitalize()}")
print(f"Computer chose: {computer_choice.capitalize()}")
if user_choice == computer_choice:
return "It's a Tie!"
elif (user_choice == "rock" and computer_choice == "scissors") or \
(user_choice == "paper" and computer_choice == "rock") or \
(user_choice == "scissors" and computer_choice == "paper"):
return "You Win!"
else:
return "You Lose!"
def play_game():
"""
Runs a single round of the Rock, Paper, Scissors game.
"""
print("\n--- Rock, Paper, Scissors ---")
user_choice = get_user_choice()
computer_choice = get_computer_choice()
result = determine_winner(user_choice, computer_choice)
print(result)
def main():
"""
Main function to run the Rock, Paper, Scissors game, allowing multiple rounds.
"""
print("Welcome to Rock, Paper, Scissors!")
while True:
play_game()
play_again = input("\nDo you want to play again? (yes/no): ").strip().lower()
if play_again != 'yes':
print("Thanks for playing! Goodbye.")
break
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()