我的目标是打印未来20年的闰年。
到目前为止没什么特别的。
我的问题是:
如何将
while
替换为for
def loop_year(year):
x = 0
while x < 20:
if year % 4 != 0 and year % 400 != 0:
year +=1
##print("%s is a common year") %(year)
elif year % 100 != 0:
year +=1
print("%s is a leap year") % (year)
x += 1
loop_year(2020)
答案 0 :(得分:6)
parent:__contruct
这很简单 - for i in range(20):
print(i)
是计数器,i
函数调用定义了它可以拥有的值集。
在您的更新中:
您不需要来替换该循环。 range
循环是正确的工具 - 您不想从0到20枚举while
的所有值(如x
循环那样),您要执行一段代码,而 x&lt; 20。
答案 1 :(得分:5)
如果您要求的是在迭代集合时有索引,那就是enumerate
的用途。
而不是:
index = -1
for element in collection:
index += 1
print("{element} is the {n}th element of collection", element=element, n=index)
你可以写:
for index, element in enumerate(collection):
print("{element} is the {n}th element of collection", element=element, n=index)
修改强>
回答原来的问题,你要问这样的事吗?
from itertools import count
def loop_year(year):
leap_year_count = 0
for year in count(year):
if (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0):
leap_year_count += 1
print("%s is a leap year") % (year)
if leap_year_count == 20:
break
loop_year(2020)
那就是说,我同意ArtOfCode,while
- 循环似乎是这个特定工作的更好工具。