[Tutor] Python type confusion?

Danny Yoo dyoo at hashcollision.org
Tue Sep 29 01:34:45 CEST 2015


On Mon, Sep 28, 2015 at 1:27 PM, Ken Hammer <kfh777 at earthlink.net> wrote:
> A simple "type" problem?
>
> The following code works as a py file with the XX'd lines replacing the two later "raw_input" lines.
> Why do the "raw_input" lines yield a TypeError: 'str' object is not callable?  Same result if I use/omit
> the parens around the poly tuple.


As C Smith notes, raw_input() returns a string.  As the name suggests,
it treats its input as raw text, and does not try to interpret it as
data.

Interpreting text as data isn't too bad if we follow certain
conventions.  One of the most popular conventions is to treat the text
as JavaScript object notation (JSON), because basically everything
knows how to parse JSON these days.  We can use the 'json' module to
parse JSON-encoded text.

For example, here's some sample use of the json.loads() string-parsing
function from the interactive interpreter:

#######################################
>>> import json
>>> json.loads('[0.0, 0.0, 5.0, 9.3, 7.0]')
[0.0, 0.0, 5.0, 9.3, 7.0]
>>> json.loads('42')
42
#######################################

The main limitation here is that this knows how to handle lists, but
it doesn't know how to handle tuples, since there's no such thing as
tuples in JSON.  Hopefully that isn't too painful for your case, but
let us know if it is.


To use this parser for your own program, add the import to the top of
your program:

#########
import json
#########

and then wrap a use of json.loads() around each of the raw_input()
calls.  Like this:

##########################################
import json

poly = json.loads(raw_input("Type, 0.0-n ,"))
x = json.loads(raw_input("Type your val of x, "))

# ... rest of program here
##########################################


Hope this helps!


More information about the Tutor mailing list