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():
    i=73
    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():
   i=73
   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.2008-06-12)

435.   What is a lezzie lad or dyke dude? (lezzielad and dykedudes unite!)   [jake/2006-06-19]
347.   How can I boot KNOPPIX off my hard drive?   [strick/2003-02-15] ( jake/2003-02-20 )
309.   What does the YAK do about SPAM?   [strick/2002-02-26]
256.   How does the new Windows Product Activation (WPA) scheme work?   [rupe/2001-07-10]
157.   In the intro to the Everclear song "A.M. Radio", what does the reference to KHJ Radio, Los Angeles refer to?   [rupe/2001-01-01]
154.   How can I integrate PGP5 functionality into the pine mail reader?   [rupe/2000-12-27]
129.   What do all the diferent colors of manic panic hair dye look like?   [jesse/2000-10-07]
99.   Can I legally use electronic countermeasures on my vehicle in California?   [rupe/2000-05-23]
37.   What is this "goo" that holds the yak together?   [robey/2000-02-01]