Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Sam Dale6,136 Points
Using Multiple "== statements" vs "or statements"
Hi there. This is a simple question, but Python has the weird and unique ability to do crazy stuff like 3 < x < 5 checks. So Kenneth has a line:
if monster == door or monster == start or start == door:
The line that follows could do the same thing in a more concise way:
if monster == door == start:
I know functionality-wise it doesn't work and this is an oddity that applies only to Python, but is the second way more Pythonic? Or is the first one more clear? Thanks!
Chris FreemanTreehouse Moderator 68,064 Points
Your first condition will stop evaluating at the first matching pair since the other matches can not make the result any more True:
monster == door or monster == start or start == door
The second condition
monster == door == start
This is equivalent to
# monster == door and monster == start and start == door # not correct monster == door and door == start # correction by pointed out by @[Jason Anello](https://teamtreehouse.com/jasonanello)
That is, it's True only if they all match. But if you reverse the comparison, it will be True only if they all differ:
>>> start = 2 >>> door = 4 >>> monster = 6 >>> start, door, monster (2, 4, 6) >>> start == door == monster False >>> start != door != monster True
EDIT: as pointed out by Jason Anello this is equivalent to
start != door != monster # is equivalent to start != door and door != monster
As mentioned further down, adding an additional round-robin case fixes it:
start != door != monster != start # is equivalent to start != door and door != monster and monster != start
Note: This is a only a syntax curiosity. The Pythonic way is to spell it out with the long form.
start != door and door != monster and monster != start # OR start == door and door == monster and monster == start
depending on your goals.
Nathan Tallack22,159 Points
Just remember, the moment it gets match it will stop evaluating.
So for your first one it will never check your third conditional if the first or second match.
For your second one it will only work if all three match.