Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading