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

Question:

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.

Asked By: Right.Orphée

||

Answers:

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")
Answered By: Samwise
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('rps')
    if user in 'rps':   
        if user != computer:
            if user + computer in ('pr', 'sp', 'rs'):  
                userScore += 1
            else:
                computerScore += 1
        print(f"you({userScore}): {user}  |  computer({computerScore}): {computer}n")
        game -= 1
    else:
        print(f"'{user}' is not valid, try again")

if userScore > computerScore:
    print("You Won")
elif computerScore > userScore: 
    print("You Lost")
else:
    print("Drawn")
Answered By: Right.Orphée
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.