12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

3.15. Exercises 27Here’s an example that usesdo_twicetocall a function namedprint_spamtwice.def print_spam():print 'spam'do_twice(print_spam)1. Type this example intoascriptand testit.2. Modify do_twice so that it takes two arguments, a function object and a value, and calls thefunction twice, passingthe value as an argument.3. Write a more general version of print_spam, called print_twice, that takes a string as aparameter and printsittwice.4. Use the modified version of do_twice to call print_twice twice, passing 'spam' as anargument.5. Define a new function called do_four that takes a function object and a value and calls thefunctionfourtimes,passingthevalueasaparameter. Thereshouldbeonlytwostatementsinthe body of this function, not four.You can see mysolutionatthinkpython.com/code/do_four.py.Exercise 3.5 This exercise 2 can be done using only the statements and other features we havelearned sofar.1. Writeafunction that draws agridlikethe following:+ - - - - + - - - - +| | || | || | || | |+ - - - - + - - - - +| | || | || | || | |+ - - - - + - - - - +Hint: toprint more than one value on aline, you can printacomma-separated sequence:print '+', '-'If the sequence ends with a comma, <strong>Python</strong> leaves the line unfinished, so the value printednext appears on thesame line.print '+',print '-'The output ofthese statements is'+ -'.Aprintstatement all by itselfends the current lineand goes tothe next line.2 Based onanexercise inOualline, Practical CProgramming, Third Edition, O’Reilly (1997)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!