I am trying to create a function for leap year and then create a generator that will function like the range(start, stop, step) command. For some reason my code below is not printing whether the written year is a leap year or not. I keep getting False when I type in known leap years and I 'm not sure what I did wrong.
def is_leap(Y):
leap=False
if Y % 4 == 0:
leap=True
elif Y % 100 == 0:
leap=False
elif Y % 400 == 0:
leap=True
return Y % 400 == 0
return Y % 4 == 0
print(is_leap(2004))
You need to return leap
. You're setting the variable, but then ignoring it.
Also, your tests are in the wrong order. If the year is divisible by 100, it will also be divisible by 4, so the first if Y % 4 == 0:
condition will be true. elif
conditions are only tested if all the previous conditions were false, so it will never perform those tests.
You don't really need the leap
variable. Just return in the if
statements.
def is_leap(Y):
if Y % 400 == 0:
return True
if Y % 100 == 0:
return False
if Y % 4 == 0:
return True
return False
In this case you don't need elif
, since return
prevents falling through to the next if
.
You can also combine all the conditions:
def is_leap(Y):
return Y % 400 == 0 or (Y % 4 == 0 and Y % 100 != 0):