-1
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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
karim
  • 15
  • 4
  • 2
    Well, `year != range(300, 2000)`. If you want to check if a value is in a range use `in`: `if year in range(300, 2000):` – Peter Wood Sep 12 '22 at 21:29
  • 3
    `year` is a single integer. `range(300,2000)` is a long sequence of integers. Equality is not possible here; it's not even a meaningful question to ask. *Containment* of an integer in the sequence is meaningful, but that's written `in`, rather than `==`. (That should at least get you some output, although your program still wouldn't have much to do with leap years.) – jasonharper Sep 12 '22 at 21:30
  • 3
    @jasonharper `range` is not a long sequence, it is a `range` object. – Peter Wood Sep 12 '22 at 21:31
  • Does this answer your question? [Determine whether integer is between two other integers](https://stackoverflow.com/questions/13628791/determine-whether-integer-is-between-two-other-integers) (specifically, see this answer: https://stackoverflow.com/a/20623994/2745495) – Gino Mempin Sep 12 '22 at 21:41

3 Answers3

0

You can do it this way simply:

def leap():
    year = int(input("enter a number: "))
    if 300 <= year < 2000:
        print(year/400)
    elif 2001 <= year < 2024:
         print(year/4)
        
leap()

Or use in instead of ==

0

The object returned by range(300, 2000) has a type that is different than year, in your case an int. We can see this in the REPL:

>>> r = r(300, 2000)
>>> r
range(300, 2000)
>>> type(r)
<class 'range'>

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:

if year in range(300, 2000):
    ...

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:

if year >= 300 and <= 2000:
    ...
Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
-1

i believe this will determine a leap year

def leap():
    year = int(input("enter a number: "))
    if year % 400 == 0:
        print('leap year')
    elif year % 4 ==0 and year % 100 != 0:
        print('leap year')
    else:
         print('not a leap year')
        
leap()
        
leap()
russj
  • 25
  • 1
  • 6