Understanding Python Functions: Definition, Polymorphism, Nesting, Scope, and Closures
This article explains Python functions, covering their definition, basic usage, polymorphism, nested functions, variable scope, global and nonlocal keywords, and closures, with clear examples and code snippets illustrating each concept for beginners.
In Python, a function is a reusable block of code that performs a specific task, allowing developers to avoid rewriting the same logic.
Example:
def my_func(message):
print('Got a message: {}'.format(message))
my_func('Hello World')Key points about functions include:
def declares a function.
The function name follows def.
Parameters are listed in parentheses.
print (or other statements) form the function body.
Functions may return a value using return or yield, or return nothing.
Polymorphism in Python functions means the same function can operate on different data types, such as integers, lists, or strings.
print(my_sum([1, 2], [3, 4])) # Output: [1, 2, 3, 4]
print(my_sum('hello ', 'world')) # Output: hello worldIf incompatible types are combined, a TypeError is raised. print(my_sum([1, 2], 'hello')) # TypeError Function nesting allows a function to be defined inside another function.
def f1():
print('hello')
def f2():
print('world')
f2()
f1()Nested functions help encapsulate logic and can improve performance for certain tasks, such as calculating a factorial.
def factorial(n):
if not isinstance(n, int):
raise Exception('input must be an integer.')
if n < 0:
raise Exception('input must be greater or equal to 0')
def inner_factorial(x):
if x <= 1:
return 1
return x * inner_factorial(x-1)
return inner_factorial(n)
print(factorial(5)) # Output: 120Variable scope in functions distinguishes between local and global variables. Variables defined inside a function are local and disappear after execution, while variables defined outside are global.
MIN_VALUE = 1
MAX_VALUE = 10
def validation_check(value):
if value < MIN_VALUE or value > MAX_VALUE:
raise Exception('validation check fails')To modify a global variable inside a function, the global keyword must be used.
MIN_VALUE = 1
def validation_check(value):
global MIN_VALUE
MIN_VALUE += 1For nested functions, the nonlocal keyword allows the inner function to modify a variable from the outer function.
def outer():
x = 'local'
def inner():
nonlocal x
x = 'nonlocal'
print('inner:', x)
inner()
print('outer:', x)
outer()Closures are functions that capture variables from their enclosing scope and return the inner function for later use.
def nth_power(exp):
def exponent_of(base):
return base ** exp
return exponent_of
square = nth_power(2)
cube = nth_power(3)
print(square(2)) # 4
print(cube(2)) # 8The article concludes with a reminder that the content is for learning purposes only.
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.
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.
