Bug With Logic Operator "or"?
Solution 1:
OR
returns the first TRUE
value it encounters.
That is:
>>> (2 or 10)
# returns 2
>>> (10 or 2)
# returns 10
Update
To address OP's comment below:
There are truthy values which evaluate to True
and there are falsey values which evaluate to False
. For example, 0 is a falsey value. Rest of the integers are truthy values. Therefore, 10 is also a truthy value.
If you do:
>>> if 10: # since 10 is truthy, this statement will execute.
print("Okay!")
else:
print("Not okay!")
# prints "Okay!"
Moving on, 10 or 2 in range(1, 6)
evaluates to 10 or (2 in range(1, 6))
.
10 or (2 in range(1, 6))
\__/ \________________/
True True
# Returns 10 because it's a truthy value.
# OR operator only evaluates until it finds a True value.
Let's see another example:
0 or 10
\_/ \__/
False True
# Returns 10 because 0 is a falsey value, so the
# OR operator continues evaluating the rest of the expression
Finally, let's see the if
expression:
>>> if 10 or 2 in range(1, 6):
print("True")
else:
print("False")
# prints "True"
It prints True
because 10 or 2 in range(1, 6)
returns 10
and as we saw above, if 10
evaluates to True
, hence, the if
block is executed.
Additionally:
The correct expression will be this:
>>> 10 in range(1, 6) or 2 in range(1, 6)
# returns True
This expression will return True
because even though 10 is not in the given range, but 2 is.
10 in range(1, 6) or 2 in range(1, 6)
\_______________/ \______________/
False True
# Returns True because OR will keep on evaluating
# until it finds a True value
But if you want to check if 10 and 2 both are in the range, you'll have to use the AND
operator:
>>> 10 in range(1, 6) and 2 in range(1, 6)
# returns False
Post a Comment for "Bug With Logic Operator "or"?"