Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Valid year function in python

Tags:

python

Here is the udacity.com web dev course, they ask to write a program for valid year, anything between 1900 and 2020 is a valid year...Now when I submit my below code it gives this error:

"Incorrect. Your submission did not return the correct result for the input '1920',. Your submission passed 7 out of 9 test cases."

my function:

def valid_year(year):
  if year and year.isdigit():
    if int(year) >=1900 and int(year) <=2020:
      return year

print valid_year('1970')

why it's not working for 1920? and the same function by udacity runs fine....Someone pls tell me what's the difference b/n both the code

Udacity function:

def valid_year(year):
  if year and year.isdigit():
    year = int(year)
    if year >=1900 and year <=2020:
      return year

print valid_year('1970')
like image 837
min2bro Avatar asked May 21 '26 05:05

min2bro


1 Answers

You need to return an int, because the udacity's function returns an integer:

def valid_year(year):
  if year and year.isdigit():
    if int(year) >=1900 and int(year) <=2020:
      return year

def valid_year_uda(year):
  if year and year.isdigit():
    year = int(year)
    if year >=1900 and year <=2020:
      return year

print valid_year('1970') == valid_year_uda('1970')
print type(valid_year('1970')), type(valid_year_uda('1970'))

output:

False
<type 'str'> <type 'int'>

This can be fixed easily just replace return year with return int(year):

def valid_year(year):
  if year and year.isdigit():
    if int(year) >=1900 and int(year) <=2020:
      return int(year)  #return an integer

print valid_year('1970')
like image 180
Ashwini Chaudhary Avatar answered May 22 '26 17:05

Ashwini Chaudhary