Master Python Functions: Definitions, Calls, Parameters, and Advanced Techniques
This article provides a comprehensive guide to Python functions, covering their definition syntax, calling conventions, parameter handling (including default, *args, **kwargs), return values, variable scope, anonymous lambda functions, and higher‑order utilities such as map, reduce, filter, and sorted, with clear code examples.
Python Functions
Functions are organized, reusable blocks of code that perform a specific task. They improve modularity and code reuse. Python offers many built‑in functions (e.g., print()) and allows you to create user‑defined functions.
1. Defining Functions
A function definition starts with the def keyword, followed by the function name and parentheses containing any parameters. The body follows a colon and is indented.
def function_name(parameters):
# function body
return [expression]2. Calling Functions
After defining a function, you can invoke it by using its name followed by arguments in parentheses.
def add(x, y):
print("{0} + {1} = {2}".format(x, y, x + y))
return x + y
add(2, 3)3. Function Parameters
Parameters listed in the definition are formal parameters; the values supplied at call time are actual arguments. Python supports default values, positional arguments, keyword arguments, and variable‑length arguments ( *args for tuples and **kwargs for dictionaries).
# Default parameters
def fun(x, y=100):
print(x, y)
fun(1) # y uses default 100
fun(1, 2) # overrides default4. Return Values
A function can return a value using return. If no value is specified, None is returned. Execution stops after return.
def greet():
print('hello world')
return 'ok'
print(123) # never executed
result = greet()
print(result) # prints 'ok'5. Variables and Scope
Variables defined inside a function are local. Variables defined at the module level are global. Use the global statement to modify a global variable from within a function.
x = 100
def inc():
global x
x += 1
print(x)
inc() # prints 101
print(x) # also 1016. Anonymous (Lambda) Functions
Lambda functions are single‑expression anonymous functions useful for short, inline operations.
multiply = lambda x, y: x * y
print(multiply(3, 4)) # 127. Higher‑Order Functions
Functions that take other functions as arguments or return them.
7.1 map()
Applies a function to each item of an iterable and returns a list of results.
def square(x):
return x * x
for i in map(square, [1,2,3,4,5,6,7]):
print(i)7.2 reduce()
Reduces an iterable to a single value by repeatedly applying a binary function.
from functools import reduce
def add(x, y):
return x + y
print(reduce(add, [1,2,3,4,5,6,7,8,9,10])) # 55
print(reduce(add, range(1, 101))) # 50507.3 filter()
Filters items of an iterable using a predicate function.
for i in filter(lambda x: x < 7, [1,2,3,4,5,40,8]):
print(i)7.4 sorted()
Returns a new sorted list from the items of any iterable.
m = {'a':1, 'c':10, 'b':20, 'd':15}
print(sorted(m.items(), key=lambda d: d[1], reverse=True))
# [('b', 20), ('d', 15), ('c', 10), ('a', 1)]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.
