📚 The CoCalc Library - books, templates and other resources
License: OTHER
"""This module contains a code example related to12Think Python, 2nd Edition3by Allen Downey4http://thinkpython2.com56Copyright 2015 Allen Downey78License: http://creativecommons.org/licenses/by/4.0/9"""1011from __future__ import print_function, division121314class Time:15"""Represents the time of day.1617attributes: hour, minute, second18"""192021def print_time(t):22"""Prints a string representation of the time.2324t: Time object25"""26print('%.2d:%.2d:%.2d' % (t.hour, t.minute, t.second))272829def int_to_time(seconds):30"""Makes a new Time object.3132seconds: int seconds since midnight.33"""34time = Time()35minutes, time.second = divmod(seconds, 60)36time.hour, time.minute = divmod(minutes, 60)37return time383940def time_to_int(time):41"""Computes the number of seconds since midnight.4243time: Time object.44"""45minutes = time.hour * 60 + time.minute46seconds = minutes * 60 + time.second47return seconds484950def add_times(t1, t2):51"""Adds two time objects.5253t1, t2: Time5455returns: Time56"""57assert valid_time(t1) and valid_time(t2)58seconds = time_to_int(t1) + time_to_int(t2)59return int_to_time(seconds)606162def valid_time(time):63"""Checks whether a Time object satisfies the invariants.6465time: Time6667returns: boolean68"""69if time.hour < 0 or time.minute < 0 or time.second < 0:70return False71if time.minute >= 60 or time.second >= 60:72return False73return True747576def main():77# if a movie starts at noon...78noon_time = Time()79noon_time.hour = 1280noon_time.minute = 081noon_time.second = 08283print('Starts at', end=' ')84print_time(noon_time)8586# and the run time of the movie is 109 minutes...87movie_minutes = 10988run_time = int_to_time(movie_minutes * 60)89print('Run time', end=' ')90print_time(run_time)9192# what time does the movie end?93end_time = add_times(noon_time, run_time)94print('Ends at', end=' ')95print_time(end_time)969798if __name__ == '__main__':99main()100101102