Functions

Lets take a look at a simple function:

>>> def sum(x, y):
...     return x+y
... 
>>> sum(5, 3)
8
>>> sum('a', 'bc')
'abc'
>>> sum('a', 5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in sum
TypeError: cannot concatenate 'str' and 'int' objects

What if the function should handle this case as well?

>>> from types import *
>>> def sum(x, y):
...     if type(x)==StringType and type(y)==IntType:
...         return x+str(y)
...     return x+y
... 
>>> sum('a', 5)
'a5'
>>> sum('Hello ', 'World!')
'Hello World!'
>>> sum(1100, 325)
1425