3
votes

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

4 Answers

3
votes

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

2
votes

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

1
votes

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.

1
votes

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]()