In this simple python program, we have to check whether the date is valid in python. It's a beginner level python program.
To understand this example, you should have knowledge of the following Python programming topics:
In this beginner python program, we need to check if a given date is valid or invalid. To check a date valid is to check the days and months are correct or not.
To check for the month validation, check the month is in between the number 1 and 12. if it is greater than 12 or less than 1, the date is not valid.
To check the day is valid or not by taking some conditions
To apply this logic in the python programming language, we are using a split date
function to split the months, day, and year separately, and then we convert them into an integer using int()
data type. Now, we use an if condition
and elif condition
in python to check all the conditions we discussed above to check the date is valid or not.
STEP 1: Accept the date from the user using the input method into a date using the date in python methods.
STEP 2: Split the date using the separator ' / ' into dd, mm, and yy.
STEP 3: Assign the values of dd, mm, and yy into the respective variable using int()
data type in python language.
STEP 4: Using an if condition
we check the month is 1, 3, 5, 7, 8, 10, or 12, and if so then assign the max value for the day as 31.
STEP 5: Using an elif
we check the month is 4, 6, 9, or 11, then assign the max value to 30.
STEP 6: Using an if
condition check for the year is a leap year or not by taking the mod as yy % 4 == 0 and yy % 100 != 0 or yy % 400 == 0. then it's a leap year so assign the max as 29.
STEP 7: Using an else
, it's not a leap year so max is 28.
STEP 8: Check the month validation by using if condition
that check month is less than 1 or greater than 12 then print the date is invalid.
STEP 9: Using elif
check the day is less than 1 or greater than our max value the print the date is not valid using python language basics.
STEP 10: Use the else statement in python language to print
the entered date is valid.
date=input("Enter the date: ")
dd,mm,yy=date.split('/') # splitting the date to day month and year
dd=int(dd)
mm=int(mm)
yy=int(yy)
if(mm==1 or mm==3 or mm==5 or mm==7 or mm==8 or mm==10 or mm==12):
max=31
elif(mm==4 or mm==6 or mm==9 or mm==11): # checking for the day is valid or not, finding max value
max=30
elif(yy % 4 == 0 and yy % 100 != 0 or yy % 400 == 0): # leap year check
max=29
else:
max=28
if(mm < 1 or mm > 12):
print("Date is invalid.")
elif(dd < 1 or dd > max):
print("Date is invalid.")
else:
print("Date you entered is valid")
Enter the date : 5/7/2016 Date you entered is valid