Master Python Functions: From Basics to Advanced Techniques
This article explores Python functions in depth, covering definitions, parameters, namespaces, multiple return values, lambda expressions, currying, generators, itertools utilities, and comprehensive error handling, providing practical code examples for data analysis and scripting.
Function Basics
Functions are the most important and fundamental way to organize and reuse code in Python. When you need to repeat similar code, defining a reusable function improves readability.
def my_function(x, y, z=1.5):
if z > 1:
return z * (x + y)
else:
return z / (x + y)Multiple return statements are allowed; if execution reaches the end without a return, None is returned automatically.
Functions can have positional and keyword arguments. Keyword arguments are useful for default values or optional parameters. Example calls:
my_function(5, 6, z=0.7)
my_function(3.14, 7, 3.5)
my_function(10, 20)
my_function(x=5, y=6, z=7)
my_function(y=6, x=5, z=7)Namespace, Scope, and Global Variables
Python uses namespaces to describe variable scope. Inside a function, variables are placed in a local namespace created at call time and destroyed after the function returns. To modify a global variable from inside a function, declare it with the global keyword.
a = None
def bind_a_variable():
global a
a = []
bind_a_variable()
print(a) # []Heavy use of globals may indicate a need for object‑oriented design.
Returning Multiple Values
Python can return multiple values in a single statement, which is actually a tuple that can be unpacked.
def f():
a = 5
b = 6
c = 7
return a, b, c
a, b, c = f()Alternatively, return a dictionary for named results.
def f():
a = 5
b = 6
c = 7
return {'a': a, 'b': b, 'c': c}Functions as Objects
Because functions are objects, they can be passed around and applied to collections. Example: cleaning a list of raw state strings.
import re
def clean_strings(strings):
result = []
for value in strings:
value = value.strip()
value = re.sub('[!#?]', '', value)
value = value.title()
result.append(value)
return result
states = [' Alabama ', 'Georgia!', 'Georgia', 'georgia', 'FlOrIda',
'south carolina##', 'West virginia?']
print(clean_strings(states))The function can also accept a list of operations to apply sequentially.
def remove_punctuation(value):
return re.sub('[!#?]', '', value)
clean_ops = [str.strip, remove_punctuation, str.title]
def clean_strings(strings, ops):
result = []
for value in strings:
for func in ops:
value = func(value)
result.append(value)
return result
print(clean_strings(states, clean_ops))Anonymous (Lambda) Functions
Lambda creates small, unnamed functions useful for one‑off transformations.
short_function = lambda x: x * 2
apply_to_list = lambda lst, f: [f(x) for x in lst]
ints = [4, 0, 1, 5, 6]
print([short_function(x) for x in ints])Lambdas are also handy for sorting by custom keys.
strings = ['foo', 'card', 'bar', 'aaaa', 'abab']
strings.sort(key=lambda x: len(set(list(x))))
print(strings) # ['aaaa', 'foo', 'abab', 'bar', 'card']Currying / Partial Application
Partial application fixes some arguments of a function, producing a new function with fewer parameters.
def add_numbers(x, y):
return x + y
add_five = lambda y: add_numbers(5, y)
# or using functools.partial
from functools import partial
add_five = partial(add_numbers, 5)Generators
Generators produce values lazily using the yield keyword.
def squares(n=10):
print('Generating squares from 1 to {}'.format(n**2))
for i in range(1, n + 1):
yield i ** 2
gen = squares()
for x in gen:
print(x, end=' ')Generator expressions provide a concise syntax.
gen = (x**2 for x in range(100))
print(sum(x for x in gen)) # 328350itertools Module
The standard library itertools offers many generator‑based utilities. Example using groupby:
import itertools
first_letter = lambda x: x[0]
names = ['Alan', 'Adam', 'Wes', 'Will', 'Albert', 'Steven']
for letter, group in itertools.groupby(names, first_letter):
print(letter, list(group))Error and Exception Handling
Use try/except to catch errors gracefully. You can catch specific exception types or a tuple of types, and use else and finally for additional control flow.
def attempt_float(x):
try:
return float(x)
except (ValueError, TypeError):
return xExample with else and finally:
f = open(path, 'w')
try:
write_to_file(f)
except Exception:
print('Failed')
else:
print('Succeeded')
finally:
f.close()IPython Tracebacks
IPython enriches error tracebacks with additional context. The %xmode magic command lets you switch between Plain, Context, and Verbose modes.
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 Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
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.
