Thread: Python 2.3

Page 2 of 2 First 12
  • Jump to page:
    #16
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2002
    Location
    Norwich, UK
    Posts
    53
    Rep Power
    12
    The python docs quickly clear this up:

    The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type.
    The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. x is not y yields the inverse truth value.
  2. #17
  3. onCsdfeu
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    Canada
    Posts
    100
    Rep Power
    11
    So, if I get it correctly,
    Code:
    x = 1
    y = 1
    if x is y:
        print 'True'
    else:
        print 'False'
    would return false, since x and y have the same value but are not the same object ? (i.e. id(x) != id(y) )
  4. #18
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2002
    Location
    Norwich, UK
    Posts
    53
    Rep Power
    12
    No, it would return print 'True' because they both automatically reference 1, which is an integer object.

    If you had:
    Code:
    x = 'test string'
    y = 'test string'
    if x is y: print 'true'
    else: print 'false'
    then it would print 'false' because those are two separate string objects.

    If you had:
    Code:
    x = 1.0
    y = 1.0
    if x is y: print 'true'
    else: print 'false'
    then it would print 'False'. I'm not entirely sure on the logic behind integers of the same value referencing the same object but floating point numbers not, but there you go. That's the way it is.

    The general idea you should get from this is that for most comparisons you'll want to use ==.
Page 2 of 2 First 12
  • Jump to page:

IMN logo majestic logo threadwatch logo seochat tools logo