Master Python Functions: Definitions, Calls, Parameters, and Advanced Techniques
This comprehensive guide explains Python functions—from basic definition syntax and calling conventions to default arguments, variable scopes, anonymous lambda expressions, and higher‑order utilities like map, reduce, filter, and sorted—illustrated with clear code examples and output results.
1. Function Definition
In Python a function is defined with the def keyword followed by the function name and parentheses containing any parameters. The body starts after a colon and is indented. An optional docstring can be placed as the first statement. pass does nothing, exit(num) terminates the program, and return [expression] ends the function and optionally returns a value.
def functionname(parameters):
# function body
return [expression]2. Function Calls
After a function is defined, it can be invoked by using its name followed by arguments in parentheses. The call can be made from another function or directly in the interactive prompt.
# example of calling a user‑defined function
add(2, 3)3. Parameters
Parameters listed in the function definition are called formal parameters (形参). Values supplied at the call site are actual parameters (实参). Python also supports default values, variable‑length positional arguments *args (a tuple) and keyword arguments **kwargs (a dict).
# default parameter example
def fun(x, y=100):
print(x, y)
fun(1) # prints: 1 100
fun(1, 2) # prints: 1 2 # *args and **kwargs example
def demo(*args, **kwargs):
print('args:', args)
print('kwargs:', kwargs)
demo(1, 2, 3, a=10, b=40)4. Return Values
A function can return any Python object using the return statement. If no value is specified, None is returned. Code after return is not executed.
def fun():
print('hello world')
return 'ok'
print(123) # never executed
result = fun() # prints "hello world" and result is "ok"5. Variable Scope
Variables defined inside a function are local to that function. The global keyword allows a function to modify a variable defined at the module level.
x = 100
def fun():
global x
x += 1
print(x)
fun() # prints 101
print(x) # prints 1016. Anonymous (Lambda) Functions
Lambda expressions create small, unnamed functions consisting of a single expression.
multiply = lambda x, y: x * y
print(multiply(3, 4)) # prints 127. Higher‑Order Functions
Python provides several built‑in higher‑order functions that accept other functions as arguments.
map()
def square(x):
return x * x
for i in map(square, [1, 2, 3, 4, 5, 6, 7]):
print(i)reduce()
from functools import reduce
def add(x, y):
return x + y
print(reduce(add, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])) # prints 55filter()
for i in filter(lambda x: x < 7, [1, 2, 3, 4, 5, 40, 8]):
print(i)sorted()
m = {'a': 1, 'c': 10, 'b': 20, 'd': 15}
print(sorted(m.items(), key=lambda d: d[1], reverse=True))
# prints [('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.
