Andy K
Andy K

Reputation: 5044

python - adding a counter in a for loop

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)     

Upvotes: 2

Views: 6236

Answers (2)

magni-
magni-

Reputation: 2055

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.

Upvotes: 8

ArtOfCode
ArtOfCode

Reputation: 5712

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.


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.

Upvotes: 6

Related Questions