Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Dates and Times in Python (2014) Let's Build a Timed Quiz App Taking The Quiz

Why use else: with for loop?

Hi All!

In the take_quiz method of quiz.py, we could have just logged the end_time after the for loop ran (successfully or not.) Since this is the case, why was it put into the else: clause? (other than just to demonstrate that it exists.)

Am I right in assuming that the main benefit is to be able to have a conditional clause that only runs if the for loop finishes successfully?

Thanks! Graham

5 Answers

Hi all,

I just stumbled on this question looking for something else(pun) and noticed after the better part of two year's it's still not answered, so thought I'd have a bash:

Basically, although 'else' when used with loops is maybe the worst possible name for what it actually does, it does have a purpose that omitting it does not.. albeit it a slightly fringe purpose.

A line of code placed after a for loop (or while loop - they have else's too) will run whenever that loop exits. We're all familiar with that - so long as an error wasn't raised, and the program continues, the line following the loop will run.

But that's not quite what the else does. It won't always run every time the for loop runs. It will only run if the for loop exhausts it's iterator and the loop ends "naturally". If we stop it early with break, it won't run. Here's my basic example of when they don't behave the same:

from math import sqrt

list_a = list(range(8, 0, -1))
list_b = [67, 43, 55, 23, 11, 78]

def is_perfect(number):
    return sqrt(number).is_integer()

def first_perfect(lst):
    for i in lst:
        if is_perfect(i):
            print("First perfect square in list is {}".format(i))
            break
    else:
        print("No perfect squares found in list")
    print("Resuming outer scope", end="\n\n")

first_perfect(list_a)
first_perfect(list_b)

Obviously this is a rushed example with limited real world use lol, but the point is there; if you want to go through a list doing x and y, but also want an option to do something specifically if you reach the natural end of the loop, the else is your friend. It doesn't mean we have to use it, most loops don't, but it is there if we need it.

Hope it helps :)

Thank you so much for explaining this! I wish I could up vote 1,000.

Graham does have a good question, and Ryan's answer, though very clearly written, does not answer it.

Yes, we know that the ELSE statement acts like a THEN, and it gets executed after the loop has run through all it's options. But why? The exact same thing is accomplished by putting the code from the ELSE block outside and after the loop.

What I (and Ryan) would like to know is, can you give an example of when putting code in an ELSE block gives different results that putting that same code after the FOR loop? Or is ELSE a useless construct?

To be specific, why is...

    for question in self.questions:
        self.answers.append(self.ask(question))
    else:
        self.end_time = datetime.datetime.now()

...preferable to the shorter and cleaner...

    for question in self.questions:
       self.answers.append(self.ask(question))
    self.end_time = datetime.datetime.now()

Don't they both give the same results? Is there any case when putting the after-the-loop code in an ELSE would give different results?

Did we ever get an answer as to why we need the else: statement after a for loop?

Bob Buethe's example is exactly what I was wondering. If anyone has any insight I'd love to hear.

Ryan Ruscett
Ryan Ruscett
23,309 Points

Hola,

That is a great question. Try ad follow me on this if possible lol.

As long is there is a question in self.questions. The loop runs.

The loop runs once. Since there is a question The loop runs twice, loop runs twice times since there is a question The loop runs thrice, loop runs three times since there is a question

BUT WAIT!

What if the loop comes back around to run a 4th time but there is no question? Now you may be thinking wait a second. For loop returns an iterator which returns all the results at once. The for loop itself knows when the loop is done. For it stopped looping.

BUT!

What if when it stopped looping I wanted to do something. Say, when the loop is finished goes all the way to the end and returns all my stuff just like I want. And I still want something to happen? If it were like VB code I could use a then statement. Except Python doesn't have one.

One method of doing something when a loop has finished is to use and else statement. So basically the code says. Run this loop and do x on all my questions. But when it's done, there is nothing left to do, I want you to THEN do ABC. Well, in python the ABC is accomplished by putting an else statement.

So the function runs and says loop done and there isn't anything left to do (Which is returned by the iterator object the for loop creates. So basically it's done, so now I want something else to run in the event it gets all the way to the bottom. We use the else statement. That is why he says really in this case an else statement really should be a THEN. Since the else statement acts like a THEN.

Does this make sense? I am not sure it makes sense to me at the moment. It's a python "thing" lol. If you totally don't understand what I am saying, please say so.

It's been a long day and tomorrow I bet I can explain it better lol.

Thanks, Ryan Ruscett.

I do understand that else works the same as a then clause, which we don't have in Python.

But my larger question still remains: Since we could just as easily put the code that's in the else statement after the for loop -- in which case it would still run once the for loop was done -- there's really no need to put it in an else clause here, right? It's just happening as a way to demonstrate to we students that the else clause exists, yeah?

A true case would be one where we don't want whatever's in the else clause to run if the for loop doesn't iterate to the end, for whatever reason, correct?

Thanks! Graham

Ryan Ruscett
Ryan Ruscett
23,309 Points

Hola,

That is a great question. Try ad follow me on this if possible lol.

As long is there is a question in self.questions. The loop runs.

The loop runs once. Since there is a question The loop runs twice, loop runs twice times since there is a question The loop runs thrice, loop runs three times since there is a question

BUT WAIT!

What if the loop comes back around to run a 4th time but there is no question? Now you may be thinking wait a second. For loop returns an iterator which returns all the results at once. The for loop itself knows when the loop is done. For it stopped looping.

BUT!

What if when it stopped looping I wanted to do something. Say, when the loop is finished goes all the way to the end and returns all my stuff just like I want. And I still want something to happen? If it were like VB code I could use a then statement. Except Python doesn't have one.

One method of doing something when a loop has finished is to use and else statement. So basically the code says. Run this loop and do x on all my questions. But when it's done, there is nothing left to do, I want you to THEN do ABC. Well, in python the ABC is accomplished by putting an else statement.

So the function runs and says loop done and there isn't anything left to do (Which is returned by the iterator object the for loop creates. So basically it's done, so now I want something else to run in the event it gets all the way to the bottom. We use the else statement. That is why he says really in this case an else statement really should be a THEN. Since the else statement acts like a THEN.

Does this make sense? I am not sure it makes sense to me at the moment. It's a python "thing" lol. If you totally don't understand what I am saying, please say so.

It's been a long day and tomorrow I bet I can explain it better lol.