Python Python Basics All Together Now Handle Exceptions

Luis Walderdorff
Luis Walderdorff
Full Stack JavaScript Techdegree Graduate 27,070 Points

How does the else statement work in this example?

I don't understand why exactly the else statement makes the function loop again when we have an error, because there is no if statement preceding it. Does the except statement count as the if in this example and if there is no error, only then it runs the rest of the code, or what is the else in reference to?

1 Answer


I am not looking at the code you are referring to, but I assume you are asking about an else clause after a try...except statement in Python. If that's the case, then I can tell you the else clause is used to contain statements that you only want to execute if the try clause succeeds. You can think of it as a "no-exception" clause. Of course, if, as part of the exception handling you rethrow, break, or return, then you really don't need an else clause. But you do need else if you don't exit the block and you want some statements to execute only if the try succeeds.

Hope this helps.

Cheers, —Steve

Moderator Edit: Moved reply from Comments to Answers