2

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)     
10
  • 4
    why on earth aren't you just printing i in your for loop? Commented Apr 13, 2016 at 9:08
  • 1
    What is range(1,x = 21) supposed to do? Commented Apr 13, 2016 at 9:09
  • 1
    Tell us more about your original problem. This is wrong regardless of what you're asking. Commented Apr 13, 2016 at 9:09
  • Hi @ReutSharabani thanks for your comment. Please find my update above Commented Apr 13, 2016 at 9:21
  • 1
    @AndyK Not easily. You probably could replace it, but it wouldn't be good, concise, efficient, maintainable, or semantically correct. Commented Apr 13, 2016 at 9:35

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi @magni, sorry the for my mess. Can you have a look at my updated question, please? Thanks
you are magician. Spot on. I wish to have given you the points earlier but well, what has been given is given. Next time. Thanks again.
6
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.