5
\$\begingroup\$

I am new to Python (and to programming). I tried to implement this game in Python and took some help from the code reviews of similar questions posted on this website.

# rock paper scissors game

import random
import sys

choices = ["rock", "paper", "scissors"]

def check_victory(computer_choice, user_choice):
    if user_choice == computer_choice:
        return "tie"
    elif computer_choice == "rock" and user_choice == "paper":
        return "won"
    elif computer_choice == "paper" and user_choice == "scissors":
        return "won"
    elif computer_choice == "scissors" and user_choice == "rock":
        return "won"
    else:
        return "lost"


def play():
    # get input from user
    user_choice = None
    while user_choice not in choices:
        user_choice = input("Enter your choice: ")
        # check if user wants to quit
        if user_choice == "quit":
            sys.exit()

    computer_choice = random.choice(choices)

    # output result
    print(f"Computer choose: {computer_choice}")
    print("You " + check_victory(computer_choice, user_choice), end="\n\n")


if __name__ == "__main__":
    while True:
        play()
```
\$\endgroup\$
5
\$\begingroup\$

overall this code looks nice and tidy, and it passes pylint with minimal errors which is a good start!

Some observations:

If you're returning in an if block you don't need to use elif and/or else since on match the code will never continue. I'd probably use or instead of 3 elif statements to avoid having the `return "won" repeated. And maybe carry the result in a variable - this allows you to set a default and avoid one test. So something like:

def check_victory(computer_choice, user_choice):
    result = "lost"
    if user_choice == computer_choice:
        result = "tie"
    if computer_choice == "rock" and user_choice == "paper" or \
       computer_choice == "paper" and user_choice == "scissors" or \
       computer_choice == "scissors" and user_choice == "rock":
        result = "won"
    return result

Another thing might be to replace some of the descriptive comments with docstrings - less important in a small program, but a useful habit to get into for more complex projects later on.

Finally since you're using f-strings for the first print, you could use them for both?

print(f"Computer choose: {computer_choice}")
print(f"You {check_victory(computer_choice, user_choice)}\n\n")

Only other things are 'features' like documenting the choices available, providing 'shortcuts' like r/p/s etc - but those are 'optional extras' and nothing to do with the code quality!

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.