I'm just starting to study programming and I have a question about functions. I defined the function leapyear as follows:
def leapyear(n):
# Given a year, decide if it is a leap year or not.
if n%4==0:
if n%100==0:
if n%400==0:
return "It is a leap year."
else:
return "It is not a leap year"
else:
return "It is a leap year"
else:
return "It is not a leap year"
Now I want to use it in another function, which is going to tell me if I wrote a valid date or not (for example, 02/28/2021 is valid, but 02/29/2021 is not). What I did is this:
def valid_date():
day = int(input("Day: "))
month = input("Month: ")
year = int(input("Year: "))
if month=="January":
if day<=31:
print("Valid date")
else:
print("Not a valid date")
if month=="February":
if year%4==0:
if year%100==0:
if year%400==0:
if day<=29:
print("Valid date")
else:
print("Not a valid date")
else:
if day<=28:
print("Valid date")
else:
print("Not a valid date")
else:
if day<=29:
print("Valid date")
else:
print("Not a valid date")
else:
if day<=28:
print("Fecha válida")
else:
print("Fecha no válida")
if month=="March":
if day<=31:
print("Valid date")
else:
print("Not a valid date")
It actually gets to December, but it doesn't really matter because it is basically the same.
The code works, but I was thinking to use the leapyear function instead of writing the whole code again. How can I do that?
Thanks!
Aucun commentaire:
Enregistrer un commentaire