skip to Main Content
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


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

    Login or Signup to reply.
  2. 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:
        ...
    
    Login or Signup to reply.
  3. 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()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search