Currently doing the chapter on regex and the project asks for detecting whether the date is valid or not. I have the following code that works and doesn't work. I get these:
33/4/2022
Incorrect date
33/4/2022
0.004080118694362018
33/4/2022
0.004080118694362018
import re
months = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 30, 11: 30, 12: 31}
dateRegex = re.compile(r'''\b(
(\d{1,2}) #Day
(\-|\/|\.) #seperator
(\d{1,2}) #Month
(\-|\/|\.) #seperator
(\d{2,4})) #Year
\b''', re.VERBOSE|re.I)
datematch = dateRegex.findall(input('Please enter a date: '))
for i in datematch:
day, month, year = int(i[1]), int(i[3]), int(i[5])
def dateValidity(day, month, year):
if year < 1000 or year > 2900:
print('year incorrect')
elif (year % 4 == 0 and year % 100 != 0) or (year % 4 == 0 and year % 400 == 0 and year % 100 == 0):
months[2] = 29
elif month not in months:
print('Incorrect month')
elif day > months[month]:
print('Incorrect date')
else:
print('Date Valid')
dateValidity(day, month, year)
The output changes after the first result and the next input do not return any of the string results that i coded but only return as floats but I can't trace why. Any ideas?