Search code examples
pythonlistcoding-style

How can I clean this code ? (rock paper scissors)


I made rock paper scissors game with score counter. Although it works well, I realized that the code is too heavy.

import random

game = 3
userScore = 0
computerScore = 0

while game != 0:
    print(f"game left : {game}")
    user = input("'r' for rock, 'p' for paper and 's' for scissors : ")
    computer = random.choice(['r', 'p', 's'])
    if user != computer:
        if user == 'p' and computer == 'r' or user == 's' and computer == 'p' or user == 'r' and computer == 's':
            userScore += 1
        else:
            computerScore += 1
    else:
        userScore += 0
        computerScore += 0
    print(f"you({userScore}) : {user} & computer({computerScore}) : {computer}\n")
    game -= 1
if userScore > computerScore:
    print("You Won")
elif computerScore > userScore: 
    print("You Lost")
else:
    print("Drawn")

I am trying to clean up this code so that it is more readable and soft.


Solution

  • A few changes you can make to the main loop that make it a little simpler:

    # use 'for' and 'range' to iterate over a sequence of numbers
    for game in range(3, 0, -1):
    
        print(f"game left : {game}")
        user = input("'r' for rock, 'p' for paper and 's' for scissors : ")
        # an iterable of single-character strings can be swapped for a single string
        computer = random.choice('rps')
    
        if user != computer:
            #  use 'in' to concisely test a bunch of different possibilities
            if user + computer in ('pr', 'sp', 'rs'):
                userScore += 1
            else:
                computerScore += 1
        # eliminate 'else' that doesn't do anything
    
        print(f"you({userScore}) : {user} & computer({computerScore}) : {computer}\n")