Lecture Date: Monday, March 14
We will continue talking about functions today. We will write a few new functions and cover some specific nuances of function usage:
- calling a function from another function
- local and global variables
- variable name collision
- keyword parameters
- global variables vs. global constants
- how to test a function
- returning multiple values
Let’s consider some different types of functions:
Functions might or might not
return a value
return - that’s what happens when they reach the end or finish by using the keyword
return. The difference is some bring back to the place where they were called some value of something. Others don’t - we call these
Some functions have effects, even if they are
print(text). This function is technically
void - it does not return anything. However, it does print stuff to the screen. A function can have an effect on the system even if it does not return a value. We will see this more when we consider how parameters are passed by value or passed by reference.
You can call functions from other files
The point of a library is to provide a set of functionality with functions that you can use in your program. You can then
import that library in to a bunch of different programs. It’s completely reusable.
When you invoke a function, the following happens in order:
- A new piece of memory (called a “stack frame” or “activation record”) is created.
- The parameters of the function are created in that new memory.
- The parameters you pass in to the function invocation get copied into the new memory’s parameters in order.
- We note where we left off running the old function
- We stack the new memory on top of the old memory, covering up the old memory completely
- We start running the code in the new function’s body
When you return from a function, either with the
return keyword or by reaching the end of the body, the new memory is removed (“popped”) from the stack, leaving us with the calling function’s memory.
Let’s watch and see what happens at the Python Tutor Visualizer!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
1 2 3 4 5 6 7 8
No Audio Today due to malfunction