Search code examples
pythonfunctiondebuggingtypeerrorprocedure

Arithmetic with the Result of Python Procedures


I have defined a procedure in python which outputs a number, and would like to add the results of calling the procedure on two different inputs. However, when I try to perform arithmetic on the result of a procedure, I am presented with the error message,

TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'.

I tried using the int() function, but apparently this cannot operate on 'NoneType' results. How would I go about adding the two results?

The segment of the code in question is:

def leapYear(year):
    if year % 4 != 0:
        year = 365
    else:
        if year % 100 != 0:
            year = 366
        else:
            if year % 400 != 0:
                year = 365
            else:
                year = 366

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    dpY = leapYear(year2) - leapYear(year1)

It's part of my attempted solution for a problem on Udacity (I'm relatively new to coding).


Solution

  • You need to explicitly return the result of the function you wish to use. Therefore, you need to add the following line to the end of your leapYear function:

    return year
    

    with a single level of indentation.

    Complete example:

    def leapYear(year):
        if year % 4 != 0:
            year = 365
        else:
            if year % 100 != 0:
                year = 366
            else:
                if year % 400 != 0:
                    year = 365
                else:
                    year = 366
        return year
    
    def daysBetweenDates(year1, month1, day1, year2, month2, day2):
        return leapYear(year2) - leapYear(year1)
    

    If a value is not returned explicitly, a Python function returns a None value.

    That being said, you can make your life easier by using the datetime module, and in particular the datetime.timedelta objects.