Python "if X == Y and Z" syntax

Viewed 106905

Does this:

if key == "name" and item:

mean the same as this:

if key == "name" and if key == "item":

If so, I'm totally confused about example 5.14 in Dive Into Python. How can key be equal to both "name" and item? On the other hand, does "and item" simply ask whether or not item exists as a variable?

8 Answers

@Manoj is correct in describing the behavior and specifies the correct equivalent statement. however, i would wish to discuss short circuiting ie the mechanics of what is evaluating.

x and y is short hand for

if x:
  return y
else:
  x

evaluation goes:

if key == "name" and item:

key == "name" and item will evaluate first.

if key != "name" then we will return False and the condition is evaluated upon this value and no action occurs.

however if key == "name" we will return item. item now becomes the condition of the if loop

if item:
 # action :: do something

and action specified underneath the if block will then follow if item also exists.

Related