views:

374

answers:

7

Does this

if key == "name" and item:

mean 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?

Thanks.

+23  A: 

if key == "name" and item: means if (key == "name") and (item evaluates to True).

Keep in mind that (item evaluates to True) is possible in several ways. For example if (key == "name") and [] will evaluate to False.

Manoj Govindan
Thanks! It reminds me a little bit of isset in PHP.
paracaudex
@paracaudex: No!! After `$b = 0;`, `isset($b)` evaluates to true, but `$b` is false. And `isset(true)` is nonsense, while `while True` is *the* way to write an infinite loop.
delnan
@paracaudex: A better equivalent to isset($b) in Python would be ("b" in locals() or "b" in globals()). But that would be somewhat strange and unusual Python; normally the set of variables in scope when particular code runs should be statically predictable.
poolie
+3  A: 

No, you have to repeat the expression. It evaluates as 2 separate conditions, and checks if both are true -

  1. x == y
  2. z

Check the Python documentation for a list of what is considered False in Python

(However, interesting to note that, as opposed to other languages, the following:

if 3 < x < 6

is equivalent to

if x > 3 and x < 6

)

froadie
A: 

If you look at the code for example 5.14:

def __setitem__(self, key, item):         
    if key == "name" and item:            
        self.__parse(item)                
    FileInfo.__setitem__(self, key, item)

item is a variable, similar to how key is.

It can be used in the if statement if it evaluates into either true or false.

eg.

happy = True
name = "Peter"
if name == "Peter" and happy:
    print name + " is happy!"
Victor Neo
A: 

Manoj explained it well. Here goes some complementary notes.

The pseudocode

if key == "name" or if key == "item":

can be get this way:

if key == "name" or key == "item":

An interesting idiom to do it is:

if key in ("name", "item"):

but it is more useful for really great conditions where you just want to know if some value is equal to any other value from a list.

brandizzi
You mean `or`, not `and`.
Just Some Guy
You are right, I corrected it! Thank you!
brandizzi
+1  A: 

Others have explained how the expression you're asking about is evaluated. An important thing to know is that if the first operand of the "and" operator evaluates to false, the second one is never evaluated, because the result of "and" is always false if one operand is false, and if you know the first operand is false, then the whole "and" is false and you don't have to evaluate the second. This is called "short-circuiting" and applies to "or" as well as "and" (except that "or" is always true when either operand is true, so the second operand is evaluated only when the first is false).

The other thing you need to know is that the result of the whole "and" operation is the value of the last operand evaluated. Since things other than the literal constants True and False are considered logically true or false, this fact (combined with short-circuiting) can be used as a substitute for "if" statements in some situations, and you will occasionally see it used that way.

For example, "x or y" evaluates to x if x is true, but to y if x is false. Sometimes this is used to provide defaults for missing values:

name = raw_input("Enter your name: ") or "dude"
print "Hello, %s!" % name

If you don't enter anything at the prompt, just hit Enter, the return value of raw_input is the empty string, "", which is considered false. Since the left branch of the "or" is false, it doesn't short-circuit, and the right branch is evaluated, so the result of the "or" is "dude." If you do enter a value at the prompt, the right branch never gets evaluated, due to short-circuiting, and so the value of the "or" is whatever you entered.

A lot of people consider abusing Boolean operators this way to be poor style now that Python has "x if y else z," but this particular use strikes me as readable enough. (But this is about the only one!) "The value is this, or that if it's empty." Compare it to the following:

name = raw_input("Enter your name: ")
name = name if name else "dude"
print "Hello, %s!" % name
kindall
+1  A: 

If, hypothetically, you did want

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

you could do this

if key == "name" == item:
Dave Aaron Smith
A: 

@Victor Neo: Also you do not need separate boolean:

for happy in (False, "Peter", '', "Susan" , []):
    print(happy + ' is happy.' if happy else 'Everybody is bored.')

If statement is preferred over using or and and with non-booleans, which emulated the effect before value if condition else value became available in Python.

Tony Veijalainen