Functions and variables
A variable declared inside a function is local and exists only in that function: when the function ends it disappears, and if it is used outside a NameError appears. A variable declared outside functions (in the main program) is global and can be read inside a function. To change the value of a global variable in a function, global name must be written at the start of the function; otherwise Python considers the name local and b = b + 1 gives an UnboundLocalError. A parameter is also a local variable: if k = 7 is passed to a function, doubling the parameter inside does not change the outer k. Global variables can make a program confusing, so it is better, where possible, to pass values by parameters and return the result with return. Local variables protect a value from being spoiled by accident elsewhere.
| Local variable | Global variable | |
|---|---|---|
| Declared | inside a function | outside functions |
| Exists | only in that function | can be read everywhere |
A pupil’s notebook had a rough page and a clean page. What is on the rough page belongs only to that page, while what is on the clean page may be needed in many places. Local and global variables are separated in the same way.
Programmers, project managers and system designers decide which value stays inside and which is shared.
Write two lists: “needed only today” and “needed every day”. Then explain in one sentence which is like local and which like global.
1def f(): 2 t = 7 3 print(t) 4f() 5print(t)
7 NameError
1hisob = 0 2def oshir(): 3 global hisob 4 hisob = hisob + 1 5oshir() 6oshir() 7print(hisob) 8 9def f(n): 10 n = n * 2 11 print(n) 12k = 7 13f(k) 14print(k)
2 14 7
“The circle boundary”: the classroom is a “function” – a circle of desks; a pupil inside uses the card in the hand (local) only in this circle, while the writing on the board (global) is seen by everybody. The teacher asks questions to find who can see what.
1x = 1 2def f(): 3 x = 2 4 print(x) 5f() 6print(x)