Exercises
We’re going to start coding more sophisticated programs in this session. Be sure to check Appendix C if you get stuck, and be sure to start writing your code in module files. You won’t want to retype some of these exercises from scratch if you make a mistake.
Basics. At the Python interactive prompt, write a function that prints its single argument to the screen and call it interactively, passing a variety of object types: string, integer, list, dictionary. Then try calling it without passing any argument: what happens? What happens when you pass two arguments?
Arguments. Write a function called
adderin a Python module file.addershould accept two arguments and return the sum (or concatenation) of its two arguments. Then add code at the bottom of the file to call the function with a variety of object types (two strings, two lists, two floating points), and run this file as a script from the system command line. Do you have to print the call statement results to see results on the screen?varargs. Generalize the
adderfunction you wrote in the last exercise to compute the sum of an arbitrary number of arguments, and change the calls to pass more or less than two. What type is the return value sum? (Hints: a slice such asS[:0]returns an empty sequence of the same type asS, and thetypebuilt-in function can test types.) What happens if you pass in arguments of different types? What about passing in dictionaries?Keywords. Change the
adderfunction from Exercise 2 to ...