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')