[Tutor] Is this correct?
Hoffmann
oasf2004 at yahoo.com
Sun Apr 16 01:39:43 CEST 2006
--- Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> Hi,
>
> > The goal is to write a function printTime that
> takes a
> > Time object as an argument and prints it in the
> form
> > hours:minutes:seconds.
> >
> > So, I wrote the script below:
> >
> > class Time:
> > pass
> >
> > hour = int( raw_input('Enter the hour: ') )
> > min = int( raw_input('Enter the minute: ') )
> > sec = int( raw_input('Enter the sec: ') )
> >
> > time = Time()
> > time.hours = hour
> > time.minutes = min
> > time.seconds = sec
>
> Personally I prefer to put the initialisation
> intomnan __init__()
> method, but otherwise it looks ok to me. Also I'd
> probably
> not use a class here but a simple tuple or similar,
> but your
> exercise seems to want an object and implies a class
> should be used.
>
> > def printTime(time):
> > print 'The time is %dh:%dmin:%dsec' % (hour, min,
> > sec)
> >
> > printTime(time)
>
> HTH,
>
> Alan G
> Author of the learn to program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
Hi Alan,
Thanks for your comments. Please, see below a new
version of that exercise. What do you think?
Thanks,
Hoffmann
ps: the new version:
hour = int( raw_input('Enter the hour: ') )
min = int( raw_input('Enter the minute: ') )
sec = int( raw_input('Enter the sec: ') )
class Time:
def __init__(self, hours = 0, minutes = 0, seconds =
0):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
def printTime(self): # By convention, the first
parameter of a method is called self.
'''printTime:
Prints the time.'''
print str(self.hours) + ":" + str(self.minutes) +
":" + str(self.seconds)
def convertToSeconds(t):
''' convertToSeconds:
Converts a Time object into an integer.'''
minutes = t.hours * 60 + t.minutes
seconds = t.minutes * 60 + t.seconds
return seconds
def makeTime(seconds):
''' makeTime:
Converts from an integer to a Time object.'''
time = Time()
time.hours = seconds/3600
seconds = seconds - time.hours * 3600
time.minutes = seconds/60
seconds = seconds - time.minutes * 60
time.seconds = seconds
return time
def addTime(t1, t2):
''' addTime function:
Calculates the sum of two times.'''
seconds = convertToSeconds(t1) + convertToSeconds(t2)
return makeTime(seconds)
currentTime = Time()
currentTime.hours = hour
currentTime.minutes = min
currentTime.seconds = sec
currentTime.printTime()
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
More information about the Tutor
mailing list