☰ Contents · Computing

Local and global variables, the GCD (EKUB) function

Lessons 49–50 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
49

Functions and variables

Textbook: pp. 96–98
GoalKnows the difference between local and global variables, uses the global keyword, and understands that if a parameter changes inside a function the outer variable does not change.
New words
local variable: a variable created inside a function; it exists only there · lokal o‘zgaruvchiglobal variable: a variable created outside functions; it can be read everywhere · global o‘zgaruvchiglobal: the keyword that lets a function change a global variable · globalscope: the part of the program where a name can be used · ko‘rinish doirasi
Explanation

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.

Worked examples
A local variable: def f(): ⏎     t = 7 ⏎     print(t) ⏎ f() ⏎ print(t) f() prints 7 and then the last print(t) gives a NameError, because t exists only inside f.
global and a parameter: hisob = 0 ⏎ def oshir(): ⏎     global hisob ⏎     hisob = hisob + 1 ⏎ oshir() ⏎ oshir() ⏎ print(hisob) thanks to global hisob the function changes the outer hisob; after two calls 2 is printed. A parameter: def f(n): ⏎     n = n * 2 ⏎     print(n) ⏎ k = 7 ⏎ f(k) ⏎ print(k) it is 14 inside, while k stays 7 outside.
Class activity

“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.

Practice
1
Which error appears if b = b + 1 is done in a function without writing global?
2
What does this program print? x = 1 ⏎ def f(): ⏎     x = 2 ⏎     print(x) ⏎ f() ⏎ print(x)
3
Write a function oshir(x) that increases b = 5 by 1 without global and return the result to b.
4
Why is it advised to use global variables as little as possible?