HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerateCanonical

Rock, Paper Scissors game in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scissorspapergamerockpython

Problem

I wrote a simple Rock, Paper Scissors game in Python for class. As a beginner, I would like some input as to how I could abstract or make my code smoother. I feel like the repeated use of if or elif statements are overbearing. I would like any tips or advice, or perhaps a different method of approach.

import random
user = ''

while user != 'q':
    print('Enter your choice')
    print('R or r for rock\nP or p for paper\nS or s for scissors\nQ or q to quit')
    user = input('')
    user = user.lower()
    if user == 'q':
        break
    comp = random.randrange(1, 4)
    choice = comp

    # assign (int) to user choices
    if user == 'r':
        user = 1
    elif user == 'p':
        user = 2
    elif user == 's':
        user = 3

    # assign string to computer random choice
    if   comp == 1:
        choice = 'rock'
    elif comp == 2:
        choice = 'paper'
    elif comp == 3:
        choice = 'scissors'

    print('Computer picked:', choice)

    # compare selection to figure out the winner
    if user == 1 and comp == 3:
        print('You win against the computer\n')
    elif user == 3 and comp == 1:
        print('You lose against the computer\n')
    elif user > comp:
        print('You win against the computer\n')
    elif user < comp:
        print('You lose against the computer\n')
    elif user == comp:
        print('You tie against the computer\n')

Solution

In Python you can compare multiple values the following way:

if (user, comp) in {(0, 2), (1, 0), (2, 1)} :
    print('You win against the computer\n')
elif user == comp :
    print('You tie against the computer\n')
else :
    print('You lose against the computer\n')

Code Snippets

if (user, comp) in {(0, 2), (1, 0), (2, 1)} :
    print('You win against the computer\n')
elif user == comp :
    print('You tie against the computer\n')
else :
    print('You lose against the computer\n')

Context

StackExchange Code Review Q#155571, answer score: 12

Revisions (0)

No revisions yet.