1. Basics.

    % python
    >>> def func(x): print x
    ...
    >>> func("spam")
    spam
    >>> func(42)
    42
    >>> func([1, 2, 3])
    [1, 2, 3]
    >>> func({'food': 'spam'})
    {'food': 'spam'}
  2. Arguments. Here’s what one solution looks like. You have to use print to see results in the test calls, because a file isn’t the same as code typed interactively; Python doesn’t echo the results of expression statements.

    % cat mod.py
    def adder(x, y):
        return x + y
    
    print adder(2, 3)
    print adder('spam', 'eggs')
    print adder(['a', 'b'], ['c', 'd'])
    
    % python mod.py
    5
    spameggs
    ['a', 'b', 'c', 'd']
  3. varargs. Two alternative adder functions are shown in the following code. The hard part here is figuring out how to initialize an accumulator to an empty value of whatever type is passed in. In the first solution, we use manual type testing to look for an integer and an empty slice of the first argument (assumed to be a sequence) otherwise. In the second solution, we just use the first argument to initialize and scan items 2 and beyond. The second solution is better (and frankly, comes from students in a Python course, who were frustrated with trying to understand the first solution). Both of these assume all arguments are the same type and neither works on dictionaries; as we saw in Chapter 2, + doesn’t work on mixed types or dictionaries. We could add a type test and special code to add dictionaries too, but that’s extra credit.

    % cat adders.py def adder1(*args): print 'adder1', if type(args[0]) == type(0): # integer? sum = 0 ...

Get Learning Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.