Chinedu Okonkwo
Chinedu Okonkwo

Reputation: 11

having trouble with the add

import datetime

class Time:
    def __init__(self, init_hr = 10, init_min = 30, init_ampm = "AM"):
    """
    initializes the hour, the minute, and a string indicating
    whether it's an AM or PM time
    """

        if init_hr < 1 or init_hr > 12:
            raise Exception("Error: Invalid hour for Time object")
        if init_min < 0 or init_min > 59:
            raise Exception("Error: Invalid minute for Time object")
        init_ampm = init_ampm.upper()
        if init_ampm != "AM" and init_ampm != "PM":
            raise Exception("Error: Invalid am/pm flag for Time object")
        self.hr = init_hr
        self.min = init_min
        self.ampm = init_ampm

def __add__(self, mins):
    """
    Returns the sum of a Time instance and a non-negative integer mins
    """ 
    if mins // 60 and self.hr < 12:
        div = mins // 60
        add = self.hr + div
        mod = mins % 60
        add2 = self.min + mod
        string = Time(add, add2)
        return string
    elif mins // 60 and self.hr == 12:
        div = mins // 60
        addsub = self.hr + div - 12
        mod = mins % 60
        add2 = self.min + mod
        string = Time(addsub, add2)
        return string

When I test the add function it gives me this error:

    Traceback (most recent call last):
  File "C:\Python34\problem2.py", line 313, in <module>
    print("645 minutes after   ", t3, " the time is", t3 + 645)
  File "C:\Python34\problem2.py", line 100, in __add__
    string = Time(add, add2)
  File "C:\Python34\problem2.py", line 18, in __init__
    raise Exception("Error: Invalid hour for Time object")
Exception: Error: Invalid hour for Time object

Not sure why it's giving me this error, but for times after midnight this error always occurs. Any solutions?

Upvotes: 0

Views: 38

Answers (1)

mattsap
mattsap

Reputation: 3806

The if init_hr < 1 or init_hr > 12: condition is firing. This is because add = self.hr + div is greater than 12--- "times after midnight". You may want to use a modulo operator to help wrap around. Seems you start your timing at 1. so... (time % 12) + 1

Upvotes: 1

Related Questions