Support Forums

Full Version: "==" and "is" in Python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Yesterday I was working with some code, and I used the "is" instead of the "==" as following:
Code:
import os

h = '[]>: '

while 1 > 0:
    p = raw_input(h)
    if (p is 'h?' or p is '--help'):
        h = '[h?]>: '
        print('\th?, --help\t\t\t-shows this list of commands\n\tpy?, --python\t\t\t-start interactive python in CLI\n\tpydle?, --python-idle\t\t\t')

    if (p is 'py?' or p is '--python'):
        h = '[py?]>: '
        os.system('python2.6')

    if (p is '--exit' or p is 'x?'):
        os.system('clear') and os.system('cls')
        print('Goodbye')
        break

    if (p is 'cs?' or p is '--clear'):
        h = '[cs?]>: '
        os.system('clear') and os.system('cls')
    if (p is 'lst?' or p == '--list'):
        h = '[lst?]>: '
        print(os.listdir('.'))
And it would just pass all of the if statements.... but when I replaced the "is" with the "==" it worked correctly. Any ideas? I thought they were the same operators?
It seems to be the characters used in the commands(-- and ?). I guess "is" doesn't evaluate those. Here is an example using and interactive session with python.
Code:
>>> p = 'h'
>>> if p is 'h':
    print 'hi'

    
hi
>>> p = 'h?'
>>> if p is 'h?':
    print 'hi'

    
>>> p = '--h'
>>> if p is '--h':
    print 'hi'

    
>>> if p == '--h':
    print 'hi'

    
hi
>>>
I guess it's just safer to use "==".