Alterna · учебный материал
Local variables and challenge stacks
39.2: Local variables and call stacks. Short theory, one example and Python stepways.
Что в этом материале
- How it works.
- One example in execution
- Remember
Содержание и основные понятия
Each call receives a separate stack frame with its parameters and local variables. After return, the frame is removed.
substance and practice
Grade 11
EGE No. 16
01
How it works.
Each function call receives its own frame: parameters and local variables exist before return, then the frame disappears.
Local name.
It is created within a specific call and is not visible after return.
Global name.
It is at the level of the module; reading is acceptable, change requires global.
It's a transmission.
Python transmits an object reference by assignment: the function receives a new local name for the same object.
Stack.
The last challenge that has been launched will end first.
02
One example in execution
Start the short program and go over the lines. The visualiser only shows the code, current line, variables and output.
If there's an assignment inside the function
x = ...
Python thinks
x
If you try to read the global x first and then assign it to the local x,
UnboundLocalError
I. Operator
global
It's rare: preferred parameters and return. The change in the list is visible from the outside because both names refer to the same list; the repainting of the local name is not.
Algorithm map
Read from left to right, then run the code.
1
Start
2
Transfer x to function
3
Create Local Value
4
Return New Value
5
Remove x and y
03
Remember
Don't call it "transmission-by-link": it's more accurate to transfer an object by assignment.
Differentiate the change of the object and repaint the local name.
Check the stacks when the calls are filed: each has its own parameter with the same name.
Syntax of this page
local variable
The name assigned to the function in the body belongs to the frame of this call.
global name
The level name of the module; global name allows it to be assigned from a function.
global x
Declares that x within the function is a global name; use it only when there is a clear need.
list.append
Changes the subject of the list, so the effect is visible to all names on the list.
return
Closes the frame and transmits the message.
print
It makes it possible to compare the global and the returned meaning.