by rupe

Why is my Python script returning a built in operation error?

It's most likely that you've done something like the following:

def myfunc():
    return i
out = myfunc()
print 'the number is: ' + i
The mistake seen here is a common one, and easy to make. In a language such as Python, where variables are not declared before use, and exist as untyped until given data, programmers often forget that as in other languages, variables loaded with specific types of data do have an allowable set of operations for the type.
In the code above, an attempt is made to concatenate two objects in a print statement. However, string concatenation is not allowable with integer types, which is what the return value of myfunc() was implicitly declared as when 73 was assigned to i in the function.
A better way to do this would be as follows...

import string
def myfunc():
   return i
out = myfunc()
print 'the number is' + str(i)

I just wanted to add this FQA because a coworker had this problem today, and it seems like a problem that a lot of people who are programming in Python tend to make, then bang their heads against the wall because they forget that some operations are restricted to specific types.


Read more of   The Yak's Frequently Questioned Answers   (mod.2010-02-10)

438.   What is an anarchosexual? What is Anarchosexuality?   [jake/2006-08-22]
435.   What is a lezzie lad or dyke dude? (lezzielad and dykedudes unite!)   [jake/2006-06-19]
339.   R. U. ready to Impeach the Entire Political Mainstream and Dramatically Decrease the Threat of International Terrorism?   [strick/2002-12-06]
183.   What are the real lyrics for the poem "Big Rock Candy Mountains"?   [rupe/2001-02-19] ( jesse/2001-06-29 )
160.   Where can I find information about Dr. Bronner?   [rupe/2001-01-04] ( strick/2001-01-07 )
158.   Where's a good place to start to learn about the IETF (Internet Engineering Task Force)?   [rupe/2001-01-02]
140.   What was programming the Royal McBee LGP-30 like?   [rupe/2000-10-25]
96.   Where can I find information on in-vehicle computer systems?   [rupe/2000-05-24]
39.   Can we get a peek at CRPL?   [strick/2000-02-01]
23.   What is an extropian?   [strick/2000-01-19]
18.   Where have all the flowers gone?   [datavortex/2000-01-18]
10.   are there ICKY THINGS on the internet?   [strick/2000-01-17]
9.   Where is matt.html's home page?   [strick/2000-01-18]