Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 376
Nick Boudreau Avatar asked Nov 18 '25 16:11

Nick Boudreau


2 Answers

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

like image 195
TerryA Avatar answered Nov 20 '25 07:11

TerryA


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

like image 25
svk Avatar answered Nov 20 '25 06:11

svk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!