The factorial() function first checks whether the parameter value is 0. If it is, it returns the
default definition value of 1. If the parameter value isn’t 0 , it runs a new calculation, returning the
number multiplied by the factorial of one less than the number. So the factorial() function calls
itself, each time with a lower number, until it gets to the 0 value.
Summary
In this hour, you learned how to create and use your own functions in Python. You use the def
keyword to define your function code, and then you can just reference your function anywhere in your
script code. You can return a value from the function back to the main program that called it, and you
can pass values from the main program into the function. You also learned how to work with
variables in functions. Any variable that you define inside a function can be used only inside the
function, while variables you define outside the function can be used inside the function.
In the next hour, we’ll turn our attention to modules. Python lets us use modules to package our
functions, as well as use functions from others!
Q&A
Q. Can I group all my function definitions together into a single file and then just reference
that file in my Python scripts?
A. Yes, that technique is called using a module, and it’s covered in Hour 13, “Working with
Modules”!
Q. What if you write a function that uses recursion that doesn’t have an endpoint, and your
program gets stuck in an infinite loop?
A. Python will continue to iterate through the functions until you manually stop the program by
sending a SIGINT signal to the program (using the Ctrl-C key combination).
Q. If both the function and the main program can read and process global variables, why do
I need to pass parameters to a function? Can’t I just use global variables?
A. The idea of the function is that it should be as self-contained as possible. That way you can
easily copy functions between programs. When the function uses global variables, that means
the other programs would also need to define the global variables. With parameters, all of the
data required for the function is self-contained in the function call!
Workshop
Quiz
1. What do you call the variables that are defined to receive values passed to a function?
a. Arguments
b. Parameters
c. Global variables
d. Recursion
2. A function can never reference itself. If it did, you’d get an endless loop. True or false?