Roll-your-own parser code is silly. Python has batteries included for this:
import datetime
repeat = True
datestr = raw_input('Enter a date in the format MM/DD/YYYY')
while repeat:
try:
# Parse to datetime, then convert to date since that's all you use
date = datetime.datetime.strptime(datestr, '%m/%d/%Y').date()
except ValueError:
pass # Handle bad dates in common code
else:
if 0 < date.year < 2017:
datestr = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY')
continue # Bypass invalid date input common code
# Both exception and invalid years will fall through to this common code
datestr = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY')
Obviously, as written, this doesn’t actually terminate the loop under any conditions, but neither does your original code. The advantage here is that strptime
does the heavy lifting; it validates many more things that your original code, through a single try
/except
, and handles tricky stuff like days of the month by month without special checks. You can access the year
, month
and day
attributes of the date
object it parses as before, as Python native int
s, no individual int
conversions as you go.
Note that if you wanted to use locale appropriate date representations, the format you chose happens to exactly match for en_US
locale, and you could make it more portable to non-U.S. users by just using datetime.datetime.strptime(datestr, '%x')
(though you’d have to make the raw_input
prompt dynamic to match); that works the same as '%m/%d/%Y'
for en_US
, but switches ordering and separators for, say, a German locale, which would make it equivalent to '%d.%m.%Y'
.
solved i need help adding the leap year functionality into my python program [closed]