问题描述
我必须编写一个for循环程序,要求用户输入年份和年数,首先确定输入的年份是否为闰年 ,其次输入此后的年数以检查这些是否也是闰年。
我的输出应该是这样的:
您想从哪一年开始? 1994
您要检查多少年? 8
1994年不是闰年
1995年不是闰年
1996年是闰年
1997年不是闰年
1998年不是闰年
1999年不是闰年
2000年是闰年
2001 年不是闰年
到目前为止,我的代码可以检查特定年份,但我正在努力循环它,以便它在此后的几年中继续。
这是我的代码:
print ("""Enter a year to see if it is a leap year,then enter the number of years there after you want to check""")
year_start = int(input("\nWhat year do you want to start with?\n"))
num_of_years = int(input("How many years do you want to check?\n"))
# I can't figure out the 'for loop' Syntax to loop this statement
if (year_start % 4) == 0:
if (year_start % 100) == 0:
if (year_start % 400) == 0:
print (f"{year_start} is a leap year")
else:
print (f"{year_start} isn't a leap year")
else:
print (f"{year_start} is a leap year")
else:
print (f"{year_start} isn't a leap year")
解决方法
尝试将您的代码更改为:
print ("""Enter a year to see if it is a leap year,then enter the number of years there after you want to check""")
year_start = int(input("\nWhat year do you want to start with?\n"))
num_of_years = int(input("How many years do you want to check?\n"))
# I can't figure out the 'for loop' syntax to loop this statement
for i in range(year_start,year_start + num_of_years):
if (i % 4) == 0:
print (f"{i} is a leap year")
else:
print (f"{i} isn't a leap year")
示例输出:
Enter a year to see if it is a leap year,then enter the number of years there after you want to check
What year do you want to start with?
1994
How many years do you want to check?
8
1994 isn't a leap year
1995 isn't a leap year
1996 is a leap year
1997 isn't a leap year
1998 isn't a leap year
1999 isn't a leap year
2000 is a leap year
2001 isn't a leap year
您可以使用 for
循环并使用 range
对序列进行迭代。那么你只需要(i % 4) == 0
,你不需要其他条件。
仅除以 4 不足以找到闰年。你必须检查 100 和 400。
请检查 https://en.wikipedia.org/wiki/Leap_year#/media/File:Leap_Centuries.jpg 是否为闰年。
def is_leap_year(year: int) -> bool:
# Returns True if the given year is a leap year
return bool((not year % 400) or ((not year % 4) and year % 100))
,
使用 range(num_of_years) 如下:
for i in range(num_of_years):
您应该将所有闰年逻辑封装在 for 循环中并进行一些调整,但您应该能够自己计算出来,祝您好运。