title: function description: A complete guide to Python functions: from basics to practice
#Python functions
1. Function basics: definition and abstraction
A function is not a mysterious concept - it is just a block of code that is encapsulated, can be called repeatedly, and is used to solve a single problem. From the perspective of programmers' daily development, the core value of functions lies in abstraction: you don't need to write a "add from 1 to 100" loop every time, just call it directlysum();There is no need to implement trigonometric functions from scratch every time, just usemath.sin()Just fine.
1.1 Standard definition syntax
Python usesdefkeywords to define functions. In industrial-grade code, Docstring and Type Hints are usually added - the former tells the caller what this function does, and the latter allows editors and static checking tools to know "what is passed in and what is returned", greatly improving the maintainability of the code.
1.2 Details of return value
How the result is given inside the function directly affects how the caller uses it:
- Single return: Use directly
returnJust follow the content to be returned. - Multiple return values: Write
return x, yThat's enough, Python will automatically package them into a tuple, which can be received with multiple variables when called, or indexed to obtain values. - Placeholder and empty return: If the function body has not figured out the logic yet, you can use
passPlaceholder; if not explicitly writtenreturn, or write directlyreturnIf nothing follows, Python will return by defaultNone。
2. Function call: make the code block "move"
The defined function is just a "static template" in memory and must be called to be actually executed.
2.1 Three basic calling methods
2.2 Important mechanism of parameter passing
Understanding how Python passes values to functions is more useful than simply remembering parameter names:
- Two calling methods:
- Position call:
f(a, b), the values are passed in exactly in the order of parameters when the function is defined. - Keyword call:
area_of_circle(radius=5.0), more clear, and can be passed out of order when there are many parameters.
- **What is going on at the bottom? ** Python uses object reference passing, not pure "value passing", nor pure "address passing":
- If an immutable object (number, string, tuple, etc.) is passed in, reassigning or modifying the parameter inside the function will only create a new object and will not affect the external original variables.
- If mutable objects (lists, dictionaries, collections, etc.) are passed in, the parameters will be modified in place** inside the function (such as
.append()、.update()etc.) will directly and synchronously affect external variables, which requires special attention.
2.3 Dynamic call: parameter unpacking
If you already have a list, tuple or dictionary to store parameters, you don’t need to manually separate them one by one. Use*and**You can quickly unpack:
3. Deeply understand the parameter system: rules bring freedom
Python's parameter system is very flexible, but the order of definition must be strictly adhered to, otherwise an error will be reported directly. The following is organized into a table according to priority:
4. Recursive function: simplify the logic, but be sure to pay attention to the boundaries
Recursion means that the function calls itself. The core idea is to decompose a complex problem into sub-problems with "the same structure but smaller scale".
4.1 Classic entry case: factorial
4.2 Three Golden Rules of Recursion
- There must be clear termination conditions: For example, the above
n == 1, otherwise Python defaults to a recursion depth limit of about 1000 levels (can be passedsys.getrecursionlimit()view) will be triggered. - Every recursion must be closer to the termination condition: For example, every time
nSubtracting 1, you cannot calculate further away from the end value. - Reasonably weigh performance: Recursive code is usually concise, but each call will consume function call stack space. In performance-sensitive scenarios (such as calculating very large Fibonacci numbers), it is recommended to use iteration (looping) instead of recursion.
4.3 Modern Python Optimization: Memoized Cache
Many recursions involve repeatedly calculating the same subproblem (such as finding Fibonacci numbers). Python 3.9+ provides a minimalist solution - just add a decorator!
5. Industrial best practices and specifications
To write a function, not only must it run correctly, but it must also be easy to read, modify, and reuse:
- Single Responsibility Principle: A function only does one thing. For example, you cannot "calculate area", "print results", and "save to file" at the same time.
- Naming convention: all lowercase and underlined, starting with a verb (such as
calculate_tax、validate_input)。 - Parameter verification: Use at the beginning of the function
isinstance()Check the type, use conditional statements to check the value range, and if it is unreasonable, immediately throw a clear exception (such asTypeError、ValueError)。 - Try to avoid side effects: Do not modify global variables at will inside the function, and do not directly modify the passed variable object in place - if you really need to change it, either write it clearly in the document, or return a new modified object.
6. Comprehensive practice: quadratic equation solver
Integrate the knowledge points learned previously and write a tool function that conforms to the specification:
7. Summary
Functions are the core cornerstone of Python programming: basic definitions and calls prevent code from being repeated, the flexible parameter system can adapt to various scenarios, recursion can simplify complex logic but boundary conditions must be set well, and memory caching can greatly improve efficiency in repeated calculation scenarios. Finally, remember to follow best practices - so your code can evolve from "just running" to "usable".

