简体   繁体   中英

Date validation in python

I am trying to solve a homework task involving date validation:

" What's the day? Design a program to take 3 inputs, one for day, one for month and one for year. Get your program to validate if this is an actual day, and, if it is, output the day of the week it is! "

I have done the first validation bit with the following code but can't do the second bit:

import datetime
print("This program will check if a date is correct and output what day of the week it was.")
day = input("Please input the day>")
month = input("Please input the month in number format>")
year = input("Please input the year, it must be after 1900>")
date_range = False
leap_year_check = 0

if (date in range(1,31)) and (month in range (1, 12)) and (year in range(1900, 2018)):
    date_range = True
else:
    date_range = False

if date_range == True:
    leap_year_check = year % 4

if leap_year_check == 0:
        if month == 2 and day in range(1, 29):
            print("The date entered is a correct date")
        elif month == "1" or "3" or "5" or "7" or "8" or "11" or "12" and day in range (1, 31):
            print("The date entered is a correct date")
        elif month == "4" or "6" or "10" or "9" and day in range (1, 30):
            print("The date entered is a correct date")
elif leap_year_check != 0:
        if month == 2 and day in range(1, 28):
            print("The date entered is a correct date")
        elif month == "1" or "3" or "5" or "7" or "8" or "11" or "12" and day in range (1, 31):
            print("The date entered is a correct date")
        elif month == "4" or "6" or "10" or "9" and day in range (1, 30):
            print("The date entered is a correct date")

if date_range == False:
    print("The date entered is incorrect")

Simply attempt to create it:

>>> datetime.date(2018,2,34)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: day is out of range for month

You catch the exception and consider it:

d = None
try:
    d = datetime.date(year, month, day)
except ValueError:
    print("The date entered is incorrect")
if d is not None:
    print("The date entered is a correct date")

A Python program should have the following skeleton:

# import statements
# ...

# global constants
# ...

# functions
# ...

def main():
    # TODO: the main task: parse command line arguments, etc
    pass

if __name__ == "__main__":
    main()

Now, your task is to implement date validation. Think of the big steps, and create some more functions accordingly:

def main():
    year, month, day = inputYearMonthDay()
    print(isValidYearMonthDay(year, month, day))

You already have the content of inputYearMonthDay , it could be something like this:

def inputYearMonthDay():
    print("This program will check if a date is correct and output what day of the week it was.")
    dayStr = input("Please input the day>")
    monthStr = input("Please input the month in number format>")
    yearStr = input("Please input the year, it must be after 1900>")
    return int(year), int(month), int(day)

What would be the big steps of isValidYearMonthDay ?

def isValidYearMonthDay(year, month, day):
    if not validateSaneYear(year) or not validateSaneMonth(month) or not validateSaneDay(day):
        return False

    # TODO validate days per month, with special treatment for february in leap years
    return False

validateSaneYear could be:

def validateSaneYear(year):
    if 1900 <= year < 2018:
        return True

    print("Invalid year: {}; expected to be in the range [1900,2018)".format(year))
    return False

validateSaneMonth and validateSaneDay could be implemented similarly.

And so on. If you break down the problem to its big steps, and each step to its big own big steps, you can reduce the big problem to tiny sub-problems that can be easily solved and tested individually, building up to a complete program that does something interesting. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM