0
def date(): date = input() d,m,y = date.split('/') yd400 = int(y) % 400 yd4 = int(y) % 4 yd100 = int(y) % 100 if m == '2' and d == '30': print('Invalid Date') elif m == '2' and d == '29' and (yd400 != 0 or (yd4 != 0 and yd100 == 0)): print('Invalid Date') elif d == '31' and (m == '2' or m == '4' or m == '6' or m == '9' or m == '11'): print('Invalid Date') else: print('Valid Date') 

Is there any way to simplify this part?

(elif d == '31' and (m == '2' or m == '4' or m == '6' or m == '9' or m == '11')) 

I'm writing this to verify the validity of a date inserted, without using import datetime

1
  • I would also add that you should have simple bounds as I could input m/d/y and it would pass (12/01/2014) or even nonsense (3245/3483/3859372) and it would pass. Commented Mar 7, 2015 at 12:19

2 Answers 2

4

Use a membership test against a set:

d == '31' and m in {'2', '4', '6', '9', '11'} 

Note that your in code may want to handle leading 0 characters on the month and day portions:

d, m = d.lstrip('0'), m.lstrip('0') 

so that 02/03/2015 is still seen as a valid date.

Sign up to request clarification or add additional context in comments.

5 Comments

Ohhh, if if the code is like this? (if y == 5: print(result) elif y = 20: print(ladder,y) elif y == 11: print(result) y = 35 print(ladder,y) elif y == 32: print(result) y = 68 print(ladder,y))
is it possible to simplify it?
@Lexonss: I have no idea what you are trying to do there, comments are not the place for code, really.
what i mean is if the result to be printed is different, will it be possible to be simplified?
@Lexonss: not unless you can find a pattern in the expressions that you can exploit.
0

In your example above, your code above appears to be quite happy with a plethora of incorrect input - more than 32 days any month, negative days, or negative months, year 0...

You appear to have looked into getting your leap years right, which is laudable, but a simple

datetime.datetime.strptime(input(), '%m/%d/%Y') 

would not only have "Just Worked", it is also more readable and doesn't require quite as much maintenance as what you produced above.

You asked how to do this without import datetime - that's a red flag. Somebody already did the heavy lifting, you might as well benefit from it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.