Reputation: 133
I am a bonafied noob at Python and I am writing a program that outputs whether a given date is a valid calendar date or not. I'm sure that there is much more elegant way to do it.
At this point I'm trying to figure out how I can add a variable to create a while loop that will take care of the date if it is either a leap year or not a leap year. All suggestions are quite welcome though.
I've put the problem areas of my code attempt inside <>. Here is the code I have so far:
def main():
print("This program tests the validity of a given date")
date = (input("Please enter a date (mm/dd/yyyy): "))
month, day, year = date.split("/")
month = int(month)
day = int(day)
year = int(year)
Mylist31 = [1, 3, 5, 7, 8, 10, 12]
Mylist30 = [4, 6, 9, 11]
#Calculates whether input year is a leap year or not
if year >= 100 and year % 4 == 0 and year % 400 == 0:
<it is a leap year>
elif year >= 0 and year <100 and year % 4 == 0:
<it is a leap year>
else:
<it is not leapyear>
while <it is a leapyear>:
if month in Mylist31 and day in range(1, 32):
print("Valid date")
elif month in Mylist30 and day in range(1,31):
print("Valid date")
elif month == 2 and day in range(1,30):
print("Valid date")
else:
print("Not a Valid date")
while <it is not a leapyear>:
etc...
main()
Upvotes: 1
Views: 1052
Reputation: 415
I've slightly completed your code. Hopefully from there you can keep improving it towards what you wanted.
def main():
print("This program tests the validity of a given date")
date = (raw_input("Please enter a date (mm/dd/yyyy): "))
month, day, year = date.split("/")
month = int(month)
day = int(day)
year = int(year)
Mylist31 = [1, 3, 5, 7, 8, 10, 12]
Mylist30 = [4, 6, 9, 11]
##Calculates whether input year is a leap year or not
if year >= 100 and year % 4 == 0 and year % 400 == 0:
is_leap_year = True
elif year >= 0 and year <100 and year % 4 == 0:
is_leap_year = True
else:
is_leap_year = False
if is_leap_year:
if month in Mylist31 and day in range(1, 32):
print("Valid date")
elif month in Mylist30 and day in range(1,31):
print("Valid date")
elif month == 2 and day in range(1,30):
print("Valid date")
else:
print("Not a Valid date")
else:
#TODO: validate non-leap-year date
pass
main()
Upvotes: 1