def leapyear(year):
if year/400 == int :
return False
if year/100 == int :
return False
if year/4 == int :
return True
hello I would like to know why my code doesn't work with it == to int because essentially its the same thing as using modulo and == to 0 this is just a question that came to me.
def check(n): if n > 200: return "large"
x = n/2 if x !=int: return "odd"
elif x==0 and n< 100: return "small"
elif x==0 and n>100: return "medium"
also how come the int works here
Your issue is that int
is a type
. If you try to compare a number to a type of object, which is what you are doing when you write if year/400 == int :
, it will always return False
, because these can never be the same.
A better way to check if year/400
is an integer would be:
if year%400 == 0:
return False
This is saying:
If the remainder of year/400
is equal to 0, return False
, which is what you wanted.
Some other things are:
You should use elif
instead of if
in most cases. In this one, it doesn't matter, since the return
statement terminates the execution of the function early, but you should still use it anyways. Otherwise, even when you have your final result, it will go through the rest of the if
statements.
The other thing isn't related to your code, but your leap year criteria are incorrect. If the year is divisible by 4, then it's a leap year. Unless the year is divisible by 100, then it's not. Unless it's divisible by 400, then it is.
Improved code:
def leapyear(year):
if year%400 == 0:
return True
elif year%100 == 0:
return False
elif year%4 == 0:
return True
return False