Thursday, 12 September 2013

python: calling a method with a string and input()

python: 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!

No comments:

Post a Comment