What is the function of return in python?

772 views python
2

According to my understanding?return is the meaning of returning a value.

One example, the python1 script:

def func():  
    try:  
       print 98  
       return 'ok' 
    finally: 
       print 98  

print fun()  

The output of the script is :

98

98

ok

So my question is why the output of the script is not:

98

OK

98

Why is the output of the OK line at the end?

answered question

Because the finally block is executed before the function exits and returns.

From docs: A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.

1 Answer

4

Because when you use try... finally, finally is always executed whatever happens in try block. even no exception was raised.

finally is generally used to release resources, clean up of variables etc.

posted this

Have an answer?

JD

Please login first before posting an answer.