def leap():
year = int(input("enter a number: "))
if year == range(300,2000):
print(year/400)
elif year == range(2001,2024):
print(year/4)
leap()
so I am trying to create a function that calculates if the year is a leap year, but it seems it does not want to show the answer of the leap year. there is no error message when I run the code,
also, I am doing this in visual studio code.
3
Answers
You can do it this way simply:
Or use
in
instead of==
The object returned by
range(300, 2000)
has a type that is different thanyear
, in your case anint
. We can see this in the REPL:Typically, comparing values of two types will not lead to equality. For this reason
==
is not what you’re looking for.Ranges are a builtin type in Python, which implements all the common sequence operators. This is why what you’re looking for is:
This clause will operate as you expect. Note that it does not scan the list, and is in fact take O(1) time, not O(n).
However, it is probably easier to simply see if your values are within the expected parameters using a direct integer comparison:
i believe this will determine a leap year