Nick Boudreau
Nick Boudreau

Reputation: 133

Calling a method with a string and input()

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!

Upvotes: 3

Views: 103

Answers (4)

Paco
Paco

Reputation: 4698

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

Upvotes: 1

TerryA
TerryA

Reputation: 59974

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

Upvotes: 3

Kaidjin
Kaidjin

Reputation: 1513

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.

Upvotes: 1

svk
svk

Reputation: 5919

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

Upvotes: 2

Related Questions