When I use the code:
def Jack():
global PHand
if 11 or 24 or 37 or 50 in PHand:
PHand.remove(11 or 24 or 37 or 50)
PHand.append("Jack")
I get an error saying list.remove(x) x is not in PHand, my question is, shouldn't the if check prevent this error?
-
What are you really trying to do? What's special about those numbers?Karl Knechtel– Karl Knechtel2014年02月02日 06:35:10 +00:00Commented Feb 2, 2014 at 6:35
3 Answers 3
You're basically checking to see whether 11 is true. It's non-zero, so your if always executes. What you want is:
if 11 in PHand or 24 in PHand or 37 in PHand or 50 in Phand:
Of course, your PHand.remove always tries to remove 11 for much the same reason. You can't tell remove to remove any of those (not sure where you got the idea that would even work, it's not in any documentation I've ever seen), so you should structure it so:
if 11 in PHand:
PHand.remove(11)
PHand.append("Jack")
if 24 in PHand:
PHand.remove(24)
PHand.append("Jack")
... and so on.
Of course you'd be better off refactoring that into a loop or even a function, rather than repeating all that code.
Comments
You need to iterate over each element:
for i in (11, 24, 37, 50): # assign i to 11, then 24, then 37, then 50
if i in PHand: # check each one in PHand
PHand.remove(i) # and remove that one
PHand.append("Jack") # your code
break # end the loop. remove this to check all
Otherwise, 11 or 24 or 37 or 50 in PHand outputs 11. Try it!
>>> 11 or 24 or 37 or 50 in PHand
11
Why? the way or works, it checks if the first side is truthy. If it is, it doesn't bother evaluating the rest, since the result couldn't change. If it weren't truthy, it would move on to the next argument, and so on.
And what of the in PHand? That actually gets evaluated first, to just the last number like this:
11 or 24 or 37 or (50 in PHand)
But again, 11 short-circuits all the ors.
Long story short:
or always returns a single value, not all values at once applied to functions repeatedly or however your syntax implies.
Comments
Just another way of solving it using filter:
def Jack():
T = [11,24,37,50]
found = filter(lambda x:x in T, PHand)
if found:
[PHand.remove(x) for x in found]
PHand.append('Jack')
PHand = range(10,55)
Jack()