will this work?
no it won't, because what you wrote is actually:
new_pos is "left"
→ id(new_pos) == id("left")
→ boolean value X
'right'
alone → bool('right')
→ always True
'boat'
alone → bool('boat')
→ always True
when you evaluate that expression you get: X or True or True
which always evaluates to True
. So as a result, whatever new_pos
is your function will always return True and assign new_pos
to self.man
.
Or do i need to call if new_pos for each or?
well that's a way to do it:
if new_pos is 'left' or new_pos is 'right' or new_pos is 'boat':
but that's a bit verbose, and not very elegant. A better way to write it down is to ask whether new_pos
is in the tuple ('left', 'right', 'boat')
:
if new_pos in ('left', 'right', 'boat'):
Nota Bene: even though I prefer to use is
when working with strings (as it often makes beautiful sentences like if user_input is "yes"
, be aware that this is an exceptional behaviour of the is
operator.
The is
operator is being used to match whether two instances are the same instance (i.e. the same object in memory), whereas the ==
operator checks whether the value of both instances are the same, and the ==
operator can be defined by the developer using __eq__
for custom behaviours.
This is why the is
operator is called the 'identity' operator, whereas the ==
operator is the equality
operator. Given that the id()
operator gives an unique id for an instance: you can translate a is b
into id(a) == id(b)
. Have a read of this QA for more on that.