Reputation:
Hello i am a beginner in python programming and I have to write a rock paper scissor game. However the only strings that should be typed in are rock, scissor or paper. if i check them in an if statement i have the following problem The code above keeps on giving correct as output even though I put wrong input in player1 and player2. It does not switch to the else condition.
def rps():
print "********** Rock Paper Scissors **********"
print 'what does player 1 choose?'
player1 = raw_input()
print 'what does player 2 choose?'
player2 = raw_input()
if player1 and player2 == 'rock' or 'paper' or 'scissor':
print 'correct'
else:
print 'this is not a valid object selection'
and the weird thing is that in some cases it actually does work?
Upvotes: 0
Views: 88
Reputation: 2666
Your if statement reads:
if player1 and player2 == 'rock' or 'paper' or 'scissor':
Python allows you to omit parentheses, but this is how it is parsed:
if (player1) and (player2 == 'rock') or ('paper') or ('scissor'):
Meaning, it checks for the truthiness of player1, whether player2 is 'rock', or whether 'paper' or 'scissor' are truthy.
In Python, a non-empty string is always truthy meaning 'paper' or 'scissor' will always be True
.
What you actually want is something like
if player1 in ('rock', 'paper', 'scissor') and player2 in ('rock', 'paper', 'scissor')
Upvotes: 0
Reputation: 302698
It's a valid expression, just doesn't do what you might think it does:
if player1 and player2 == 'rock' or 'paper' or 'scissor':
is checking several things:
player
player2 == 'rock'
'paper'
'scissor'
A string is convertible to bool if its non-empty. So in this case 'paper'
and 'scissor'
both evaluate as True
. Thus, we can rewrite your condition as the following, adding parenthesis for emphasis:
if (player1 and player2 == 'rock') or True or True:
Which is equivalent to
if True:
Probably not what you want to check.
Upvotes: 2