Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Using continue in a try-finally statement in a loop

Will the following code:

while True:     try:         print("waiting for 10 seconds...")         continue         print("never show this")     finally:         time.sleep(10) 

Always print the message "waiting for 10 seconds...", sleep for 10 seconds, and do it again? In other words, do statements in finally clauses run even when the loop is continue-ed?

like image 769
Andres Riofrio Avatar asked May 11 '12 03:05

Andres Riofrio


People also ask

Can you use continue in a for loop Python?

Introduction to the Python continue statementThe continue statement is used inside a for loop or a while loop. The continue statement skips the current iteration and starts the next one. Typically, you use the continue statement with an if statement to skip the current iteration once a condition is True .

Does finally execute after continue Python?

From the python docs : 'on the way out' basically means, if a continue statement is executed inside of an exception clause, the code in the finally clause will be executed and then the loop will continue on to the next iteration.

Will finally be executed after continue?

Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.

How do you end a for loop in Python?

Like the while loop, the for loop can be made to exit before the given object is finished. This is done using the break statement, which will immediately drop out of the loop and continue execution at the first statement after the block.


1 Answers

From the python docs:

When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed ‘on the way out.’ A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation — this restriction may be lifted in the future).

like image 97
Joel Cornett Avatar answered Sep 22 '22 11:09

Joel Cornett