pi@raspberrypi ~$ python3 script1210.py
The list before the function call: ['Rich', 'Christine']
The list after the function call: ['Rich', 'Christine', 'Jason']
pi@raspberrypi ~$
As you can see from the output, the modlist() function modifies the mylist list variable, which
maintains its value in the main program code.
Using Recursion with Functions
A popular use of functions is in a process called recursion. In recursion, you solve an algorithm by
repeatedly breaking the algorithm into subsets until you reach a core definition value.
The factorial algorithm is a classic example of recursion. The factorial of a number is defined as the
result of multiplying all the numbers up to and including that number. So, for example, the factorial of
5 is 120, as shown here:
5! = 1 * 2 * 3 * 4 * 5 = 120
By definition, the factorial of 0 is equal to 1. Notice that to find the factorial of 5, you just multiply 5
by the factorial of 4, and to find the factorial of 4, you multiply 4 by the factorial of 3. You continue
on until you get to the factorial of 0, which, by definition, is 1. This is a perfect example of using
recursion in your functions.
Try It Yourself: Creating a Factorial Function Using Recursion
To use recursion, you need to define an endpoint in the function so that it doesn’t get
stuck in a loop. For the factorial function, the endpoint is the factorial of 0:
if (num == 0):
return 1
Follow these steps to create the factorial function code:
- Create the file script1211.py, and open it in your editor program. Here’s the code to
use for the file:
Click here to view code image
#!/usr/bin/python3
def factorial(num):
if (num == 0):
return 1
else:
return num * factorial(num - 1)
result = factorial(5)
print('The factorial of 5 is', result)
- Save the file, then run the program.
When you run the script1211.py program, you get this output:
Click here to view code image
pi@raspberrypi ~$ python3 script1211.py
The factorial of 5 is 120
pi@raspberypi ~$