Chapter 9 (functions) Flashcards
what can be used to check for global and local variables?
globals()
locals()
- These variables act as dictionaries that store the key (variable name) with its value (assigned data to the variable)
What is variable scope?
How accessible a variable is to sections of code:
- if a variable is local, it can only be accessed within the function, if it is global it can be accessed anywhere in the code
What are the 3 types of scope?
Built-in scope:
- can be accessed anywhere with no restrictions, they are the built-in names of python: str(), int(), etc.
Global scope:
- variables that have been declared outside of functions
Local scope:
- only accessible in a function
In what order are variables checked in a function?
- Local
- Global
- Built-in
What is namespace?
maps (like a dictionary) of names of objects in a given scope
What is scope resolution?
The process of searching namespace for a name,
- looking for a variable in the dictionary of names
How does python interpreter restrict variable scope?
assigning variables to a namespace
Can the same name be in multiple namespaces?
Yes
Will there be an error if I define a list as list() since it is already a built-in name?
No because it is going to be defined as a global or local variable which are read before the built-in names
Can immutable objects be edited inside a function?
no, the object will not be edited, instead a new object will be made in the local scope of the function with the values assigned to it instead of editing the global variable
Can mutable objects be edited inside a function?
Yes they can, for example a list or dictionary, however, only edited, not replaced.
- index overwriting is fine, but straight up changing the whole list all at once will not impact the list
what would be the output of:
def modify(list):
‘’’ docstring ‘’’
list[1] = 99
my_list = [1,2,3]
modify(my_list[:])
print(my_list)
[1,2,3] because the argument is actually a copy of my_list not the real list
When preassigning values to parameters, what must be true?
All parameters that have preassigned values must be in the correct order
Can you put the arguments in any order when calling a function?
Sometimes, only when the parameter is specified = a value
What is an arbitrary parameter?
When the number of parameters cannot be predicted, so the function excepts more than normal all stored in an arbitrary parameter