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

3
  • Possibly related: stackoverflow.com/q/275018 Commented May 10, 2015 at 1:48
  • @Nemo: raw_input() doesn't include the newline, no. Commented May 10, 2015 at 1:48
  • @MartijnPieters: Whoops. Not particularly "raw", then, is it? Commented May 10, 2015 at 1:49

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

That worked! Thanks! I thought "is" was the same as "==" in python, but I guess there's some slight difference
"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.
Whoops, that's what I get for not paying attention to the changing sort order! I edited your answer instead of mine, sowwy.
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!
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.

3 Comments

Related to your previous answer here: stackoverflow.com/questions/13650293/… ;)
awesome, thanks for the explanation! Switching it worked but I was wondering why it wouldn't be the same, that makes sense.
@Zulu: Thanks for saving me from searching! :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.