3

I'm brushing up on my Python and I'm a little confused about something, the following code does not work as intended:

def a():
    print "called a"

def b():
    print "called b"

dispatch = {'go':a, 'stop':b}
dispatch[input()]()

When I type the word go into the console, I get "NameError: name 'go' is not defined", but when I type 'go' (with the quotes) it works fine. Is input() not returning a string? And if not, then shouldn't using str() convert the input to a string?

When I change the code to:

dispatch[(str(input())]()

I still get the same behaviour.

note: I'm using Python2.7 if it makes a difference.

Sorry if this is obvious, it's been a few years since I've used Python!

4 Answers 4

3

input() in Python 2.7 is equivalent to:

eval(raw_input())

Hence, you should use raw_input() in python 2.7 to avoid such errors, as it will not try to evaluate the input given.

Because you add in quotation marks, Python interprets this as a string.

Also, note that raw_input() will return a string, so there will be no point in calling str() around it.


Note that in Python 3, input() acts like raw_input() did in Python 2.7

Sign up to request clarification or add additional context in comments.

3 Comments

I read a list of the more 'notable' changes between 2.X and 3.X but this one wasn't listed, thanks!
@NickBoudreau Hmm, where abouts was this? There's a great list at the docs if you wish to check it out :)
I can't remember the site, it was just someone's blog I think, but I wrote down the changes they listed: strings are now unicode, print is a function not a statement, range is removed and replaced with xrange, division of integers results in a float and all classes are now new-style. Thanks for the link, very useful!
2

You want raw_input(). input() evaluates the user's input as Python code.

Comments

1

Use raw_input(). input() is equivalent to eval(raw_input()), so when you type go without quotes, python tries to eval go and fails. With the quotes, it eval's the string (ie. returns it) which will work to index your dict.

raw_input will work in every case.

Comments

1

You can also use this:

def go():
    print "called a"


def stop():
    print "called b"

input()()  # Equivalent to eval(raw_input())()
# OR
my_function = input()
my_function()  # Might be easier to read

# Another way of doing it:

val = raw_input()
globals()[val]()

Comments

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.