My aim is to print the next 20 leap years.
Nothing fancy so far.
My question is :
how to replace the
whilewith afor
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)
If what you're asking about is having an index while iterating over a collection, that's what enumerate is for.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With