Understanding Python Variables, Scope, References, Lambda Functions, and Recursion
This article explains Python's local and global variables, how to modify globals within functions, demonstrates variable referencing, introduces anonymous lambda functions, and illustrates recursion with factorial examples, providing code snippets for each concept.
Section 1 introduces local and global variables in Python, defining local variables as those declared inside a function with scope limited to that function, and global variables as accessible by all functions. It explains that when a name is defined both locally and globally, the local definition takes precedence, and that the global keyword is required to modify a global variable inside a function unless the variable is mutable (e.g., list or dict).
Code demonstration of variable scope:
c = 3 # global variable, accessible by all functions
a = 2
def Test():
b = 2 # local variable, only inside the function
global a # declare a as global to modify it
a = 4
print('{}'.format(a))
pass
def Test2():
c = 4
print('{}'.format(c))
pass
Test2()
print(c) # shows that the global c is unchanged
Test()
print(a) # shows that a changed after declaring it global
# mutable types (list, dict) can be modified without global
listA = []
print(type(listA))
def demoList():
listA.append('python') # add data to the empty list
pass
demoList()
print(listA) # outputs the modified list
# immutable types (str, tuple, numbers) cannot be altered in the same waySection 2 discusses object references in Python, showing how the id() function can be used to inspect whether two variables refer to the same object in memory. It demonstrates that mutable objects retain their address when modified inside functions, while immutable objects receive a new address when reassigned.
li = []
print('Original address {}'.format(id(li)))
def Test(n):
li.append([1, 3, 'chen'])
print(id(n))
print('Inside {}'.format(n))
pass
print(id(li))
Test(li) # the address remains the same
print('External variable object {}'.format(li))
# immutable example
a = 1
def func(x):
print('x initial address {}'.format(id(x)))
x = 2
print('x address after change {}'.format(id(x))) # new address for immutable int
print(x)
pass
print('a address {}'.format(id(a)))
func(a)
print(a)Section 3 introduces anonymous (lambda) functions, explaining that they are defined with the lambda keyword, consist of a single expression, implicitly return the expression's value, and are limited to simple logic.
M = lambda x, y: x + y
print(M(2, 3)) # M acts like a regular function
# conditional expression inside lambda
Test = lambda x, y: x if x > y else y
print(Test(2, 3))
# single‑argument lambda
Test = lambda x: x ** 2
print(Test(10))Section 4 covers recursion, defining it as a function calling itself, requiring a clear base case to avoid infinite loops, and noting advantages (simple logic) and disadvantages (risk of stack overflow, high memory usage). It provides both an iterative and a recursive implementation for calculating factorials.
def jiecheng(n):
result = 1
for item in range(1, n + 1): # range is half‑open, so include n
result *= item
return result
print(jiecheng(5))
# recursive version
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.