Nate Brunelle Today: Functions again, Scope CS1110 Nate Brunelle Today: Functions again, Scope
Questions?
Last Time Functions
Advice on functions Define function in one file, use in another Good names Usually an action phrase You usually don’t want functions with side effects Don’t use print, instead return a str Don’t use input, instead use parameters Use docstrings Tell you why a function exists How to use that function
Visualizing Programs http://www.pythontutor.com/visualize.html
Scope Scope- The area where a variable has meaning Usually: variable is in scope when it is created onward. Functions: variable is in scope only in the function in which it is defined
What happens when you invoke a function? Create memory for the function Copy argument values into parameter names Do what the function says Know what to return, then return it Remove the memory for the function
Which variable v is in scope? If the variable v is available in the local scope, use that one If the variable v is not available in the local scope, use the variable v available in the global scope If a function ever will have the local variable v, you can only use that variable v
Global variables Allow you to have something “remembered” from one run of a function to another.