[英]python - adding a counter in a for loop
My aim is to print the next 20 leap years. 我的目标是打印下一个20年的leap年。
Nothing fancy so far. 到目前为止还算不上什么。
My question is : 我的问题是:
how to replace the
while
with afor
如何用for
替换while
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)
for i in range(20):
print(i)
It's that easy - i
is the counter, and the range
function call defines the set of values it can have. 就是这么简单- i
是计数器, range
函数调用定义了它可以具有的一组值。
On your update: 关于您的更新:
You don't need to replace that loop. 您无需替换该循环。 A while
loop is the correct tool - you don't want to enumerate all values of x
from 0-20 (as a for
loop would do), you want to execute a block of code while x < 20. while
循环是正确的工具-您不想枚举x
到20之间的所有x
值(就像for
循环那样),您想在 x <20 时执行代码块。
If what you're asking about is having an index while iterating over a collection, that's what enumerate
is for. 如果您要问的是在遍历集合时有一个索引,那就是enumerate
目的。
Rather than do: 而不是:
index = -1
for element in collection:
index += 1
print("{element} is the {n}th element of collection", element=element, n=index)
You can just write: 您可以这样写:
for index, element in enumerate(collection):
print("{element} is the {n}th element of collection", element=element, n=index)
edit 编辑
Responding to the original question, are you asking for something like this? 在回答原始问题时,您是否要求类似这样的内容?
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)
That said, I agree with ArtOfCode that a while
-loop seems like the better tool for this particular job. 就是说,我同意ArtOfCode的观点,对于特定的工作, while
循环似乎是更好的工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.