Chapter 4: Modules (Solutions to Even-Numbered Exercises)

Question 2

>>> import calendar
>>> help(calendar.isleap)
Help on function isleap in module calendar:

isleap(year)
    Return 1 for leap years, 0 for non-leap years.
>>> help(calendar.leapdays)
Help on function leapdays in module calendar:

leapdays(y1, y2)
    Return number of leap years in range [y1, y2).
    Assume y1 <= y2.
>>> calendar.leapdays(2000, 2051)
13
>>> help(calendar.weekday)
Help on function weekday in module calendar:

weekday(year, month, day)
    Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
    day (1-31).
>>> calendar.weekday(2016, 7, 29)
4

Question 4

We are using the string formatting operator; '%.6f' % sqrt(8) says to convert the result of sqrt(8) to a string.

Question 6

import media
pic = media.load_picture(media.choose_file())
media.show(pic)
media.show(pic)

Question 8

import media
pic = media.load_picture(media.choose_file())
for p in pic:
    media.set_green(p, media.get_green(p) / 2)
media.show(pic)

Question 10

import media
pic = media.load_picture(media.choose_file())
for p in pic:
    media.set_red(p, media.get_red(p) * 2)
media.show(pic)

ValueError: Invalid red value specified.

Question 12

a) This is more difficult to test because floating-point results are subject to roundoff error.

b) test_distance is arbitrarily saying that two numbers are "close enough" if they are less than one millionth apart. First, that value is completely arbitrary. Second, if left and right are both always less than a millionth, for example, this test will always pass, regardless of how accurate the answer is.