Tuesday 15 July 2014

Unexpected behavior from Python -



Unexpected behavior from Python -

i'm new python , bit confused way python treats empty object.

consider code piece;

a = {} if a: print "a alive!" else: print "a not alive!" if not a: print "not a!" else: print "a!" if none: print "a none!" else: print "a not none!"

i next output code piece.

a not alive! not a! not none! edit::

i under assumption object initialized {} valid object. why doesn't python treat way? , why diff output diff if conditions?

edit 2::

in c++, when say

object obj; if (obj){ }

it come in if block if obj not null(regardless if garbage value or whatever)

but same thing when translate python.

a = {} #this valid object if a: # doesn't work!

why? , read python evaluates {} false. why that?

i see nil weird in output. let's go step-by-step:

a dictionary, more dictionary object; a dictionary, it's empty, truth value false

therefore:

the first if, since a false, prints else statement , that's right; the sec if, since not a evaluates true because a false, prints if part , that's right too. last, not to the lowest degree a not none object, dict object, it's right else part taken , printed.

python python-2.7

No comments:

Post a Comment