Home > front end >  code does not want to print when i run it
code does not want to print when i run it

Time:09-13

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.

CodePudding user response:

That's not how range works, nor is it how the equality operator works.

You first need to convert the range object to a list:

list(range(300, 2000))

You then need to check whether the year is contained within the list:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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()
  • Related