17.13: Exercises

Think Python 2ed. · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC 3.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    17.13: Exercises

    Exercise \(\PageIndex{1}\)

    Download the code from this chapter from http://thinkpython2.com/code/Time2.py. Change the attributes of Time to be a single integer representing seconds since midnight. Then modify the methods (and the function int_to_time) to work with the new implementation. You should not have to modify the test code in main. When you are done, the output should be the same as before.

    Solution

    http://thinkpython2.com/code/Time2_soln.py

    Exercise \(\PageIndex{2}\)

    This exercise is a cautionary tale about one of the most common, and difficult to find, errors in Python. Write a definition for a class named Kangaroo with the following methods:

    1. An __init__ method that initializes an attribute named pouch_contents to an empty list.
    2. A method named put_in_pouch that takes an object of any type and adds it to pouch_contents.
    3. A __str__ method that returns a string representation of the Kangaroo object and the contents of the pouch.

    Test your code by creating two Kangaroo objects, assigning them to variables named kanga and roo, and then adding roo to the contents of kanga’s pouch.

    Download http://thinkpython2.com/code/BadKangaroo.py. It contains a solution to the previous problem with one big, nasty bug. Find and fix the bug.

    If you get stuck, you can download http://thinkpython2.com/code/GoodKangaroo.py, which explains the problem and demonstrates a solution.


    This page titled 17.13: Exercises was last modified on Tue, 01 Dec 2020 03:30:55 GMT and is shared under a CC BY-NC 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) via source content that was edited to the style and standards of the LibreTexts platform.