Updating time
Related code
class Time: """Represents the time of day. attributes: hour, minute, second """ def set(self, hour, minute, second): self.hour = hour self.minute = minute self.second = second def print(self): print(f"{self.hour:02}:{self.minute:02}:{self.second:02}") def add(self, other): sum = Time() sum.hour = self.hour + other.hour sum.minute = self.minute + other.minute sum.second = self.second + other.second if sum.second >= 60: sum.second -= 60 sum.minute += 1 if sum.minute >= 60: sum.minute -= 60 sum.hour += 1 return sum start = Time() start.set(9, 0, 0)
Sometimes it is useful for a function/method to modify the objects it gets as parameters. In that case, the changes are visible to the caller. Functions that work this way are called modifiers.
increment, which adds a given number of seconds to a Time object, can be written naturally as a modifier.
class Time: ... def increment(self, seconds): self.second += seconds if self.second >= 60: self.second -= 60 self.minute += 1 if self.minute >= 60: self.minute -= 60 self.hour += 1
Is this function correct? What happens if seconds is much greater than sixty?
>>> start.increment(3661) >>> start.print() 09:01:3601
When we added 3661 seconds we expected 10:01:01 but got 09:01:3601.
In such case, it is not enough to carry once; we have to keep doing it until
self.second
and self.minute
are less than sixty.
In such case we can use while
instead of if
.
class Time: ... def increment(self, seconds): self.second += seconds while self.second >= 60: self.second -= 60 self.minute += 1 while self.minute >= 60: self.minute -= 60 self.hour += 1
>>> start.increment(3661) >>> start.print() 10:01:01
Exercises
Rewrite correct version of increment so it does the correct thing even if seconds is much greater than 60.
Rewrite correct version of increment that doesn't contain any loops.
Hint: modulus and floor division
Now write a "pure" version of increment that creates and returns a new Time object rather than modifying the parameter.