Problems Understanding Conditions In If Statement Python
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
Solution 1:
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.
Solution 2:
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')
Post a Comment for "Problems Understanding Conditions In If Statement Python"