Python Variable Scope, References, Lambdas & Recursion Explained
This article explains the differences between local and global variables in Python, how to modify globals with the global keyword, the behavior of mutable and immutable objects, demonstrates variable scope with code examples, and also covers references, lambda anonymous functions, and recursive implementations such as factorial calculations.
Local and Global Variables
Local variables are defined inside a function and are only visible within that function; different functions can have variables with the same name without interfering with each other. Global variables are defined at the module level and can be accessed by any function. If a global and a local variable share the same name, the local one takes precedence. To modify a global variable inside a function, declare it with the global keyword. For mutable types such as list or dict, the object can be modified inside a function without global because the object's address does not change.
c = 3 # global variable
a = 2
def Test():
b = 2 # local variable
global a
a = 4
print('{}'.format(a))
def Test2():
c = 4
print('{}'.format(c))
Test()
print(a) # a changed because declared global
listA = []
def demoList():
listA.append('python')
# modifies the global list without global keyword
demoList()
print(listA) # ['python']References
In Python, values are passed by object reference; the id() function shows the memory address of an object. For mutable types like lists and dictionaries, the address remains the same when modified inside a function.
li = []
print('original address {}'.format(id(li)))
def Test(n):
li.append([1, 3, 'chen'])
print(id(n))
print('inside {}'.format(n))
Test(li) # address unchanged
a = 1
def func(x):
print('x start address {}'.format(id(x)))
x = 2
print('x after change address {}'.format(id(x)))
func(a) # a unchangedAnonymous Functions (lambda)
Lambda creates a function without a name. It can contain only a single expression, which is implicitly returned. Lambdas are suitable for simple operations but cannot replace multi‑statement functions.
M = lambda x, y: x + y
print(M(2, 3))
Test = lambda x, y: x if x > y else y
print(Test(2, 3))
Test = lambda x: x**2
print(Test(10))Recursion
Recursion is a function calling itself and must have a clear termination condition. It simplifies logic but can cause stack overflow if not careful.
def jiecheng(n):
result = 1
for item in range(1, n+1):
result *= item
return result
print(jiecheng(5))
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
print(factorial(5))Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
