-2

I have made this code to emulate a rock paper scissors game. I have a procedure which has the main game, and when I run this by itself without the if loop at the end, it works. However, when I try to validate whether or not the user entry is numerical, it does not print the correct message. Here is the full code:

import random
def game(choice):
    number = random.randint(1,3)
    if choice == 1 and number == 2:
        print("You lose.")
    if choice == 1 and number ==3:
        print("You win.")
    if choice == 1 and number == 1:
        print("It is a draw")
    if choice == 2 and number == 3:
        print("You lose.")
    if choice == 2 and number ==1:
        print("You win.")
    if choice == 2 and number == 2:
        print("It is a draw")
    if choice == 3 and number == 1:
        print("You lose.")
    if choice == 3 and number ==2:
        print("You win.")
    if choice == 3 and number == 3:
        print("It is a draw")  
x = input("Choose 1 (rock), 2 (paper) or 3 (scissors).")
digit = x.isdigit()
if digit == True:
    game(x)

By the way, there is no error message, the procedure just does not work!

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172

1 Answers1

0

First of all, there are a few issues with your code. If you wish to ignore, skip to Error Handling for answer to your question. You will find it in there.

Naming Variables

Your variables do not tell a person reading your code what they are. If you showed someone the word number, they would not know that it is what the computer chooses in rock paper scissors. Same with choice (who's choice?) and even more so x. So why don't we name them computer_choice, user_choice and choice respectively. I know these are a bit longer to type, but it is worth sacrificing a few extra keystrokes for a bit more clarity. Also notice that I used snake_case name formatting as per usual Python standards.

Repetitiveness/ game()

Your game function could do with a bit of re-doing. All you need is a general 'formula' for winning and losing. In this case, losing is when (thanks to @Brett Beatty) if computer_choice == (user_choice + 1) % 3, drawing is when computer_choice == user_choice and winning is everything else. Also, when your code is being played, the user only knows if they have won or lost, and not what the computer chose, so to add a bit more clarity, I added a list and another print() line. This feature is also useful to test code. Additionally, use zero-based variable values, such as in the computer_choice and user_choice variables. This is useful when converting values to list indexes. Below is a revised version of your code that i have made which includes all points above (I have also made it a function, as you will see below - I just think it looks better):

import random


def game(user_choice):
    user_choice -= 1
    rps = ["Rock", "Paper", "Scissors"]
    computer_choice = random.randint(0, 2)
    print("You: {} Computer: {}".format(rps[user_choice], rps[computer_choice]))
    if user_choice == computer_choice:
        return 0
    elif computer_choice == (user_choice + 1) % 3:
        return -1
    else:
        return 1

Error Handling

To make sure the user enters an integer, you would have to add int() around the input statement. However, this alone would return ValueError if the value entered by the user is not an integer, and this is a problem. However, there is a way to fix this using try: except: else: blocks, as you will see below. This is what you would need to decide if the value is an integer, it also prints the correct message when it is not. I also think this is what you wanted for if digit == True(FYI you would only need if digit if you were to do it that way).

def main():
    while True:
        try:
            value = int(input("Choose 1 (rock), 2 (paper) or 3 (scissors):"))
        except ValueError: # If any part of the code in the try block raises a ValueError
            print("Not an integer")
        else:  # If error is not raised
            if not 1 <= value <= 3: # If value is not between 1 and 3
                print("Must be between 1 and 3")
            else:
                result = game(value) # sets result to return value from game()
                break
    if result == 1:
        print("You Win")
    elif result == -1:
        print("You Lose")
    else:
        print("It's a Draw")

And Finally, the 'if loop'?

Let me just make this clear. There is no such thing as an if loop!!! An if statement runs code **ONCE** if a certain condition is True. I think what you want is a while loop. This runs code **REPEATEDLY** as long as a certain condition is True. In the code below, I created a while True loop, which runs the code each time the user types in "y", and breaks from the loop if not.
Also, use if __name__ == '__main__'. It exists in Python so that Python files can act as either reusable modules, or as standalone programs. It also looks more complex, if you want to look smart.

if __name__ == '__main__':
    while True:
        main()
        if input("Again? Yes(y) No(Anything else): ").lower() != 'y':
            break

Example Output (ignore colours):

Choose 1 (rock), 2 (paper) or 3 (scissors):1
You: Rock Computer: Scissors
You Win
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):3
You: Scissors Computer: Scissors
It's a Draw
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):2
You: Paper Computer: Paper
It's a Draw
Again? Yes(y) No(Anything else): n

Process finished with exit code 0

Also, for the OP, if you haven't already, I would recommend downloading Pycharm. It is completely free, and makes coding a lot easier. It also improves presentation too. It picks up on some of the things mentioned above, as well as keeping your code in line with PEP guidelines.

AJ123
  • 194
  • 2
  • 14