The formal definition of recursion is an algorithmic technique where a function, calls itself to perform part of a task. A good example of recursion is the factorial function n!. Recursive solutions have two main parts:
A recursion function pauses, and calls itself just like calling any other function. In this way the functions stack on each other, until reaching the base case. Then it returns a value from the base case and teh functions pop back to the original function call.
python example of recursive factorial function:
def factorial( n ):
if n <1: # base case
return 1
else:
return n * factorial( n - 1 ) # recursive call
A lot of things can go wrong when you write a program. For example, you can have the following exceptions errors in Python
To avoid these errors, you could put check in for different possibilities like os.path.isfile or
os.path.exists. However trying to cover all possibilities could take quite a lot of
time. Alternatively you could go ahead and try and deal with problems as they happen. This is exactly what a
try statement does. The Syntax is similar to an if statement.
python example of an if statement
try:
fin = open('bad_file')
for line in fin:
print line
fin.close()
except:
print 'Something went wrong.'
Python begins by executing the try clause. If all goes well, it will skip the except clause and continue.
However if something goes wrong, it will pause, jump out of the try clause and run the
except clause. Handling an exception with a try statement is called catching
an exception. Catching an exception gives us an opportunity to fix the problem, or try again, or at
least end the program gracefully.
There are a couple of ways the try clause can be used. You may not have a except
clause at all and use it as a brute force method to continue your program. You can use
except Exception: to avoid catching system exceptions like SystemExit or
KeyboardInterrupt Some code may use except: pass, however this may not be good
practice. Generally when you find an error, you should do something to handle it i.e. write it in a log file
. Further two principles of the Zen of Python are: Explicit is better than implicit and
Errors should never pass silently.