1

I am trying to write a program that determines leap years. My problem is that I cannot convert the year variable into an integer. I attempt to parse the variable in the try statement. the error I am receiving is

line 19, in divide_by_4
if (year%4) == 0:
TypeError: not all arguments converted during string formatting

My code is below: and the file I imported in only had 1804 in it

def is_year(year):
    '''determine if the input year can be converted into an integer'''
    try:
        int(year)
        return year
    except ValueError:
        print("current year is not a year")

def divide_by_4(year):
    if (year%4) == 0:
        return True

def divide_by_100(year):
    if (year % 100) == 0:
        return True

def divide_by_400(year):
    if (year % 400) == 0:
        return True


def leap_year(year):
    if is_year(year):
        if divide_by_4(year):
            if divide_by_100(year):
                if divide_by_400(year):
                    return True
            else:
                if divide_by_400(year):
                    return True


def main():

    input_file = input("Enter the file input file name: ")
    output_file = input("Enter the output file name: ")

    try:
        file_in = open(input_file, 'r')
    except IOError:
        print("The input file could not be opened. The program is ending")

    try:
        file_out = open(output_file, 'w')
    except IOError:
        print("The output file could not be opened. The program is ending")

    for years in file_in:
        if leap_year(years):
            file_out.write(years)
    file_in.close()
    file_out.close()

main()    

2 Answers 2

1

How about:

def divide_by_4(year):
    if (int(year) % 4) == 0:
        return True

Justification: In is_year function you don't actually convert String to int. Instead you just check if it is possible to convert it. That's why you need to make actual conversion ( int(year) ) before you use year as integer.

The same problem will occur in divide_by_100.

Sign up to request clarification or add additional context in comments.

Comments

0

when you read data from file, the data's type is string , so you can't use year % 4. you can do like that:

def leap_year(year):
    if is_year(year):
        year = int(year)
        ......

then do it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.