3 回答
TA贡献1895条经验 获得超3个赞
鉴于您正在尝试做的事情,我相信这是一种方法,将for您传递给函数的元素的循环(以列表格式)与if-elif-else您陈述的条件相结合。
years = ["25", "1955", "2000", "1581", "1321", "1285", "4365", "4", "1432", "3423", "9570"]
def isLeap(years):
for i in years:
if int(i) >= 1583:
print(i, "Is a Gregorian Calendar Year.")
elif int(i) < 1583:
print(i, "Is not a Gregorian Calendar Year.")
elif int(i) % 400 == 0 or int(years[i]) % 4 == 0:
print(i, "Is a Leap Year.")
elif int(i) % 400 == 1 or int(years[i]) % 4 == 1:
print(i, "Is NOT a Leap Year.")
else:
print("Test cannot be performed.")
isLeap(years)
输出:
25 Is not a Gregorian Calendar Year.
1955 Is a Gregorian Calendar Year.
2000 Is a Gregorian Calendar Year.
1581 Is not a Gregorian Calendar Year.
1321 Is not a Gregorian Calendar Year.
1285 Is not a Gregorian Calendar Year.
4365 Is a Gregorian Calendar Year.
4 Is not a Gregorian Calendar Year.
1432 Is not a Gregorian Calendar Year.
3423 Is a Gregorian Calendar Year.
9570 Is a Gregorian Calendar Year.
TA贡献1851条经验 获得超4个赞
您应该在isLeap
函数之外进行从 string 到 int 的转换:
for year in map(int, years):
你的函数应该接受一个年份参数:
def isLeap(year)
你的测试应该是:if year >= 1583 # etc.
但是,这里还有一个逻辑问题:因为您使用的是if/elif
,所以您永远无法确定某事是否是闰年,因为您的前两个 if 语句中的一个总是正确的。(它要么 >= 1583,要么 < 1583;不会检查其他条件。)
TA贡献1779条经验 获得超6个赞
将字符串列表转换为整数列表可以通过列表推导简单地完成:
int_list = [int(year) for year in years]
代码中另一个明显的问题是理解变量的范围并将 args 传递给函数。
如果您迭代多年,则将年份项目传递给您的函数并在函数范围内使用
def isLeap(year):
...
for int_year in int_list:
isLeap(int_year)
添加回答
举报