Reputation: 33
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
Upvotes: 0
Views: 54
Reputation: 54273
To check membership in a list, use the in
operator.
if d > 30 and m in [4, 6, 9, 11]:
Upvotes: 1
Reputation: 39072
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")
Upvotes: 2