Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - adding a counter in a for loop

Tags:

python

My aim is to print the next 20 leap years.

Nothing fancy so far.

My question is :

how to replace the while with a 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)     
like image 746
Andy K Avatar asked Aug 10 '26 17:08

Andy K


1 Answers

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.

like image 90
magni- Avatar answered Aug 13 '26 08:08

magni-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!