Chapter 2: Problem 13
Recursion A useful feature of user-defined functions is recursion, the ability of a function to call itself. For example, consider the following definition' of the factorial \(n !\) of a positive integer \(n\) : $$ n != \begin{cases}1 & \text { if } n=1 \\ n \times(n-1) ! & \text { if } n>1\end{cases} $$ This constitutes a complete definition of the factorial which allows us to calculate the value of \(n !\) for any positive integer. We can employ this definition directly to create a Python function for factorials, like this: def factorial \((\mathrm{n}):\) if \(\mathrm{n}==1:\) return 1 else: return \(\mathrm{n} *\) factorial \((\mathrm{n}-1)\) Note how, if \(n\) is not equal to 1 , the function calls itself to calculate the factorial of \(n-1\). This is recursion. If we now say "print (factorial (5))" the computer will correctly print the answer 120 .
Short Answer
Step by step solution
Key Concepts
These are the key concepts you need to understand to accurately answer the question.