Professor Devin Balkcom
devin@cs.dartmouth.edu
office: Sudikoff 206
A variable that is first assigned a value inside a function is a local variable.
Local variables are good. Most lines of code: compute something, and store it in a nicely named local variable. Then use that variable to compute something else, and store it in a nice local.
When a function is called, it creates a frame, an area of memory to store values of local variables. When the function returns, it destroys the frame.
Python tutor example of local variables. Or use Pycharm debugger.
Global variables are initialized outside of any function, and are placed into the global frame.
All code that relies on that global will work differently. Must use a special keyword global
to change a global within a function.
Corollary. Do not write naked code that depends on a global variable. Wrap in a function and pass parameters. Bad Brutus!
Any global variable you declare has to have a unique name. If you create a global variable x
to mean one thing, you cannot later create a variable x
to mean another.
Corollary. Do not use global variables.
There is one good use for global variables. Constants are better than magic numbers.
AVOGADRO = 6.0221415e23
In stage magic, they say that the hand is quicker than the eye.
Python is faster than either.
How can we make Python wait for the slow humans?
Types: int, float, string, function.
A function definition creates a global variable referring to a function.
A callback function is a function that you write, but never intend to call yourself. Instead, you pass it to another function for use.
Each page of the flipbook is called an animation frame.
Viewing the animation:
It is a loop, but step 3 requires that we use the callback approach. (Let the browser do the looping; we write the function.)
Model-view-controller approach:
Notice: