1

This is my function:

def mainMenu():
    print " Do you want to send a message(send) or add a name to the database(add) or exit the program(exit)?"
    answer = raw_input()
    print answer
    if answer is "send":
        sendMessage()
    elif answer is "add":
        addName()
    elif answer is "exit":
        sys.exit()
    else:
        print "Sorry, '%s' is not a valid input. Please use one 'send', 'add', or 'exit'" %answer

No matter what I enter the result in the else statement. The only thing I can really thing it is would be a problem with raw_input().

Here's a screenshot from the shell. The syntax highlighting is because I'm using sublimeREPL and it just does that, doesn't affect the code at all:

program output

I've tested all the functions that are called and they work fine individually

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Josh Gribbon
  • 75
  • 1
  • 15

2 Answers2

6

Try replacing is with ==.

For example:

In [1]: answer = raw_input()
arst

In [2]: answer
Out[2]: 'arst'

In [3]: answer == 'arst'
Out[3]: True

In [4]: answer is 'arst'
Out[4]: False
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
slcott
  • 1,194
  • 3
  • 14
  • 26
  • That worked! Thanks! I thought "is" was the same as "==" in python, but I guess there's some slight difference – Josh Gribbon May 10 '15 at 01:49
  • "is" asks if two objects are the same object. "==" asks if two objects are equivalent. "is" really is just comparing the memory address and "==" just compares what is in that address. hope that clears it up. – slcott May 10 '15 at 01:53
  • Whoops, that's what I get for not paying attention to the changing sort order! I edited your answer instead of mine, sowwy. – Martijn Pieters May 10 '15 at 01:53
  • So basically while two things may look the same they are stored separately in memory and are then not the same object. Very cool, thanks! – Josh Gribbon May 10 '15 at 01:55
3

You are using identity tests to compare strings. Users cannot possibly create the exact same string object when entering text; they create new string objects, with the same value contained, instead.

Don't use is, use == to test for equality; different objects with the same value:

if answer == "send":
    sendMessage()
elif answer == "add":
    addName()
elif answer == "exit":
    sys.exit()

See Understanding Python's "is" operator.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343