Main Content

Recursion in Python - the classic example

Archive - Originally posted on "The Horse's Mouth" - 2016-03-07 09:23:03 - Graham Ellis

A function is know as 'recursive' if it calls itself ... inherently a very dangerous thing to do, as it makes code harder to follow and debug, and you need to be 100% sure you have an "escape clause". So I normally resist giving examples on a course. However, at the tail end of last week I did put up what's known as the 'classic' example - calculating a factorial, where factoring 'n' is 'n' times factorial 'n-1' and the escape clause defines factorial 1 as 1. Source code [here].

  def factorial(val):
    if val == 1:
      return 1
    else:
      return val * factorial(val -1


Recursive code DOES have its uses - foe example when descending into an XML data structure; that's why I showed how it worked last week ,,, but the best solution if often a stack rather than recursion to such coding. Use by all means, but with care!