0

I am fairly new to coding but stuck on one of these exercises;

"Write a program that accepts a date in the format DD/MM/YYYY and output whether or not the date is valid. For example 20/07/1969 is valid, but 31/09/2012 is not."

My attempt at this:

d = int(input("Enter a day"))
m = int(input("Enter a month"))
y = int(input("Enter a year"))

if d > 30 and m == [4, 6, 9, 11]:
     print("This date is invalid")

elif d > 31:
     print ("This date is invalid")

elif m != [1,2,3,4,5,6,7,8,9,10,11,12]:
     print ("This date is invalid")

else:
     print("This date is valid")

Any suggestions on how to fix this is appreciated

3
  • 2
    I would use the date object of the datetime module. Probably not allowed, but here you also have to take leap years into account, etc. and some calendars even changed through time, making it very hard to parse it correctly without any error. For example, before 8 BC, a leap year took place every three years. Commented Oct 9, 2018 at 21:06
  • What is probably also missing is the fact that you get one string, separated with slashes, and thus you have to "split" it into three parts. Commented Oct 9, 2018 at 21:06
  • check this so link . Commented Oct 10, 2018 at 0:30

2 Answers 2

2

You were close. Just modifying your code, the correct implementation of checking an entry m against multiple options, it would look like the following. To check for multiple options, you use in, for ex. if m in [4, 6, 9, 11] instead of ==.

if d > 30 and m in [4, 6, 9, 11]:
     print("This date is invalid")
elif d > 31:
     print ("This date is invalid")
elif m not in [1,2,3,4,5,6,7,8,9,10,11,12]:
     print ("This date is invalid")
else:
     print("This date is valid")
Sign up to request clarification or add additional context in comments.

Comments

1

To check membership in a list, use the in operator.

if d > 30 and m in [4, 6, 9, 11]:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.