Home > Software design >  A TypeError prevents me from forming the conditionals of my function (Python)
A TypeError prevents me from forming the conditionals of my function (Python)

Time:04-25

The function is supposed to receive a number representing a year, and then print if it's a leap year or not.

def isItALeapYear(year):

    while True: 
        if year % 4 == 0:
            print("That is a leap year! ")
            break
    
        elif year % 4 != 0:
            print("That is not a leap year...")
            break

        elif not isinstance(year, int) or year == None:
            print("Please enter a number...")
            break

The program works, the only thing I can't get right is that it is supposed to notify you if anything that it's not a number is being used as an argument. I've tried both the isinstance() function, as well as writing what I want as year != int. And then year == None in the hopes of making it work in case anything nondefined is used as an argument.

I read this post with the exact same error: TypeError: not all arguments converted during string formatting python

But I'm not intending to format anything with the % symbol As far as I'm concerned the % can be used as an operand to get the residue of a division. So in this case I'm using it to figure out if a year is a leap year or not by asking if the residue is 0 when divided by 4. I'm pretty stuck, and the sad thing is the error comes up in the very first "if", so I can't really know if the last lines for excluding any non int type argument work or not. Any help would be really appreciated!

CodePudding user response:

First thing while loop in the function makes no sense you can remove it(If you want).

There are multiple ways to do that I will show.

First One.

def isItALeapYear(year):
    if type(year) != int:
        return         # here return to exit the function 
    while True: 
        if year % 4 == 0:
            print("That is a leap year! ")
            break
    
        elif year % 4 != 0:
            print("That is not a leap year...")
            break

        elif not isinstance(year, int) or year == None:
            print("Please enter a number...")
            break

Another is.

def isItALeapYear(year):
    try:
        int(year)
    except ValueError: # this line of code executes when the year is not the int
        return  # here return to exit the function 
    while True: 
        if year % 4 == 0:
            print("That is a leap year! ")
            break
    
        elif year % 4 != 0:
            print("That is not a leap year...")
            break

        elif not isinstance(year, int) or year == None:
            print("Please enter a number...")
            break

I know there are more ways to do that but these are the best ones (I Think).

Your function is not accurate then you can use this one.

def isItALeapYear(year):
    if type(year) != int:
        return
    if (( year@0 == 0)or (( year%4 == 0 ) and ( year0 != 0))):
        print(f"{year} is a Leap Year")
    else:
        print(f"{year} is Not the Leap Year")

Edit For Quetioner

def isItALeapYear(year):
    if type(year) != int:
        return
    if (( year@0 == 0)or (( year%4 == 0 ) and ( year0 != 0))):
        print(f"{year} is a Leap Year")
    else:
        print(f"{year} is Not the Leap Year")
try:
    isItALeapYear(asdasd)
except NameError:
    print("You give the wrong Value")

CodePudding user response:

I recommend to divide the functionality of checking the number from returning the output as well as from receiving the input.

def is_multiple_of_four(number: int):
    if number % 4 == 0:
        return True
    else:
        return False


if __name__ == '__main__':
    user_input = ""
    while not user_input.isdigit():
        user_input = input("Please type in a year: ")

    if is_multiple_of_four(int(user_input)):
        print("That is a leap year!")
    else:
        print("That is not a leap year.")

Here you can see the function that checks the number does only that, it checks the number if it's modulo of 4 equals 0. In the script outside the function you can retrieve the user input for as long as it takes to get a valid numeric and return the output in respect of the functions results.

CodePudding user response:

You could use the isleap() function from the standard library (module calendar):

from calendar import isleap

def isItALeapYear(year):
    if not isinstance(year, int):
        print("Please provide a number")
    elif isleap(year):
        print("That is a leap year!")
    else:
        print("That is not a leap year...")
  • Related