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'}Arguments. Here’s what one solution looks like. You have to use
printto 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.pydef adder(x, y): return x + y print adder(2, 3) print adder('spam', 'eggs') print adder(['a', 'b'], ['c', 'd']) %python mod.py5 spameggs ['a', 'b', 'c', 'd']varargs. Two alternative
adderfunctions 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.pydef adder1(*args): print 'adder1', if type(args[0]) == type(0): # integer? sum = 0 ...