C. F
C. F

Reputation: 13

Rock, Paper, Scissors Issue

I am creating a very simple Rock, Paper, Scissors game, using Python, but can't get past this problem. Every time I type in the answers into Command Prompt, it outputs the message 'Invalid input, try again!' which is what I have told it to do if there is an invalid input. But, I am not putting an invalid input in, this keeps printing out instead of 'Rock wins!' etc. And the 'Do you want to play again? (True or False)' prints out before the answer, and when I type True, it comes up with the Invalid input. I have tried moving around the rematch line, but nothing is working.

Here is the game, showing the error:

What's your name? Bob
And your name? Bill
 Bob, Do you want to choose rock, paper, or scissors? rock
 Bill, Do you want to choose rock, paper, or scissors? paper
Do you want to play again? (True or False) True
Invalid input, try again!

Here is my code:

import sys 

user1 = input('What\'s your name?')
user2 = input('And your name?')
user1_answer = input('%s, Do you want to choose rock, paper, or scissors?' % user1)
user2_answer = input('%s, Do you want to choose rock, paper, or scissors?' % user2)

def compare(u1, u2):
    if u1 == u2:
        return('It\'s a tie!')
    elif u1 == 'rock':
        if u2 == 'scissors':
            return('Rock wins!')
        else:
            ('Paper wins!')
    elif u1 == 'scissors':
        if u2 == 'rock':
            return('Rock wins!')
        else:
            ('Paper wins!')
    elif u1 == 'scissors':
        if u2 == 'paper':
            return('Scissors wins!')
        else:
            ("Rock wins!")
    elif u1 == 'paper':
        if u2 == 'scissors':
            return('Scissors wins!')
        else:
            ('Rock wins!')
    elif u1 == 'paper':
        if u2 == 'rock':
            return('Paper wins!')
        else:
            ('Scissors wins!')
    elif u1 == 'rock':
        if u2 == 'paper':
            return('Paper wins!')
        else:
            ('Scissors wins!')
    else:
        return('Invalid input, try again!')

rematch = bool(input('Do you want to play again? (True or False)'))

print(compare(user1_answer, user2_answer))

Upvotes: 1

Views: 203

Answers (1)

timgeb
timgeb

Reputation: 78790

You are getting "Invalid input, try again!" because your input strings are not "rock" and "paper", they are actually " rock" and " paper". You can strip whitespace from your input strings with str.strip. Also consider putting a blank at the end of your input prompts.

There are other issues with your code. For example, you never use rematch. You need to put your main logic into a while loop that breaks once rematch is false. (Consider asking for a rematch at the end of the game, not before.)

In addition, some branches of your if logic don't return anything, such as

else:
    ('Paper wins!')

which has the same effect as

else:
    pass

Upvotes: 1

Related Questions