【发布时间】:2021-03-26 07:13:17
【问题描述】:
我刚开始学习编程,我有一个关于函数的问题。我将函数闰年定义如下:
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"
现在我想在另一个函数中使用它,它会告诉我是否写了一个有效的日期(例如,2021 年 2 月 28 日是有效的,但 2021 年 2 月 29 日是无效的)。我做的是这样的:
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")
其实到了12月,不过没关系,因为基本一样。
代码有效,但我想使用闰年函数而不是再次编写整个代码。我该怎么做?
谢谢!
【问题讨论】:
标签: python function if-statement include