Reputation: 23
beginner python user here. I need to validate a date string without using the datetime() module. (hopefully, you can see) the year needs to be greater than 2021, and the date needs to be a valid date including leap years. So far I have this:
while True:
Date = input('enter date of appointment in dd/mm/yyyy format. ')
day,month,year = Date.split('/')
if month=={1,3,5,7,8,10,12}:
max_days=31
elif month=={4,6,9,11}:
max_days=30
elif year%4==0 and year%100!=0 or year%400==0:
max_days=29
else:
max_days=28
if month<1 or month>12:
print('invalid, enter a number between 1 - 12')
elif day<1 or day>max_days:
print('invalid, check day')
elif year<2022:
print('invalid, enter a year greater than 2021')
else:
break
But I'm getting the error: "not all arguments converted during string formatting" on line 10 which is "elif year%4==0 and year%100!=0 or year%400==0:"
I'm confused as to how to fix it, am I missing another formula?
Upvotes: 2
Views: 44
Reputation: 11
Your variables day
, month
and year
resulting from the Date.split('/')~ are
strings not
int`
Try the following:
while True:
Date = input('enter date of appointment in dd/mm/yyyy format. ')
day,month,year = Date.split('/')
if int(month)=={1,3,5,7,8,10,12}:
max_days=31
elif int(month)=={4,6,9,11}:
max_days=30
elif int(year)%4==0 and int(year)%100!=0 or int(year)%400==0:
max_days=29
else:
max_days=28
if int(month)<1 or int(month)>12:
print('invalid, enter a number between 1 - 12')
elif int(day)<1 or int(day)>max_days:
print('invalid, check day')
elif int(year)<2022:
print('invalid, enter a year greater than 2021')
else:
break
Upvotes: 0
Reputation: 304
The day, month and year variables are strings. This means that the when %-operator is used, the string will be interpreted as a format string. But as the strings aren't format strings, it will result in an error.
The solution is to convert the day, month and year variables to an integer.
day_string, month_string, year_string = Date.split('/')
day = int(day_string)
month = int(month_string)
year = int(year_string)
Also in the if statements where you check the maximal day count based on the month, you use if month == {1,3,5,7,8,10,12}:
this won't check if the month variable is 1, 3, 5, 7, 8, 10 or 12. To fix this other issue use if month in [1, 3, 5, 7, 8, 10, 12]
.
Upvotes: 2