adplus-dvertising

Leap Year Function (Python)

Asked 3 months ago
Viewed 20 times

I know I'm missing something very simple, but I cannot for the life of me figure it out. Here's what I have right now.

def days_in_feb(user_year):
    if user_year % 100 == 0:
        if user_year % 400 == 0:
            user_year = print(f'{user_year} has 29 days in February.')
        else:
            user_year = print(f'{user_year} has 28 days in February.')
    else:
        if user_year % 4 == 0:
            user_year = print(f'{user_year} has 29 days in February.')
        else:
            user_year = print(f'{user_year} has 28 days in February.')
    return user_year
    
if __name__ == '__main__':
    user_year = int(input())
    print(f'{days_in_feb(user_year)}')

It will run fine once but then when it goes to take the next input, I get "days_in_feb() did not return a value. Your function may be missing a return statement." I think it has something to do with reassigning user_year to those print statements in the function but without them I don't know what to return.

asked 3 months ago

Correct Answer

Instead of having the function print out your statments about the selected year, have them return a value and print then this value.

It is also okay to use longer function names and explain what the function does.

For example:

def get_days_in_feb_for_year(user_year):
    if user_year % 100 == 0:
        if user_year % 400 == 0:
            return f'{user_year} has 29 days in February.'
        else:
            return f'{user_year} has 28 days in February.'
    else:
        if user_year % 4 == 0:
            return f'{user_year} has 29 days in February.'
        else:
            return f'{user_year} has 28 days in February.'


if __name__ == '__main__':
    user_year = int(input())
    print(f'{get_days_in_feb_for_year(user_year)}')
    
answered 3 months ago

Other Answer

This makes more sense to me; not sure why you are printing in your function.

def days_in_feb(user_year):
    if is_leap_year(int(user_year)):
        return f'{user_year} has 29 days in February.'
    else:
        return f'{user_year} has 28 days in February.'

def is_leap_year(year):
    if year % 4 != 0 or year % 100 == 0 and year % 400 != 0:
        return False
    else:
        return True
    
user_year = int(input('Enter a year: '))
print(days_in_feb(user_year))
answered 3 months ago