I. What Is a Function
A function is a block of code with a specific purpose that can be called repeatedly.
During program development, it is common to encounter situations where the same logic needs to be executed repeatedly. For example:
print("欢迎使用 Python")
print("欢迎使用 Python")
print("欢迎使用 Python")
If the same logic appears repeatedly in a program, it not only causes code duplication but also makes subsequent maintenance more difficult.
The repeated logic can be encapsulated into a function:
def say_hello():
print("欢迎使用 Python")
say_hello()
say_hello()
say_hello()
With functions, a piece of code can be defined once and called repeatedly when needed.
1. Core Purpose of Functions
Code Reuse
Encapsulate repeated business logic to avoid writing the same code multiple times.
Modularity
Break down complex programs into multiple independent functions, with each function responsible for a relatively clear task.
Reduce Complexity
Callers only need to understand the function's inputs and outputs, without needing to worry about internal implementation details.
Easy to Test
Functions can be executed and verified independently, making it easier to write unit tests.
Improved Maintainability
When modifying a function's internal implementation, as long as the interface remains compatible, callers usually do not need to make adjustments.
2. Classification of Functions in Python
Common functions in Python can be divided into the following categories:
| Function Type | Description | Example |
|---|---|---|
| Built-in function | Provided by the Python interpreter | print(), len() |
| Standard library function | Provided by standard library modules | math.sqrt() |
| Third-party library function | Provided by third-party packages | requests.get() |
| Custom function | Defined by the developer | calculate_total() |
| Anonymous function | Defined using a lambda expression | lambda x: x * 2 |
| Generator function | Uses yield to produce data | def generate() |
| Asynchronous function | Defined using async def | async def fetch() |
This article focuses on the definition and invocation of ordinary custom functions.
II. Defining Functions
Python uses the def keyword to define functions.
1. Basic Syntax
def function_name(parameters):
"""Function description"""
function_body
return result
Meaning of each part:
| Component | Description |
|---|---|
def |
Keyword for defining a function |
function_name |
Function name |
parameters |
Formal parameters, can be empty |
: |
Indicates the start of the function definition |
| Function body | Code that implements the specific functionality |
return |
Returns the result, optional |
The simplest function:
def say_hello():
print("Hello, Python!")
This function has no parameters and no explicit return value.
2. Function Names
Function names must follow Python identifier naming rules.
The recommended style is snake_case, combining lowercase letters and underscores.
def calculate_price():
pass
def get_user_info():
pass
def send_email():
pass
Not recommended:
def CalculatePrice():
pass
def getUserInfo():
pass
Recommendations for naming functions:
- Use meaningful names.
- Use verbs or verb phrases where possible.
- The name should reflect the function's responsibility.
- Avoid overly broad names.
- Do not use Python keywords as function names.
- Avoid overriding important built-in function names, such as
list,str, andsum.
3. Function Body and Indentation
A function definition must be followed by a function body.
The function body is indicated by indentation, typically using 4 spaces.
def calculate_sum():
a = 10
b = 20
result = a + b
print(result)
The statements in the function body belong to the code block of that function.
The following approach will produce an indentation error:
def calculate_sum():
a = 10
b = 20
Because the function body is not correctly indented.
4. Empty Functions
Sometimes it is necessary to define a function interface first, without implementing the internal logic for the time being.
You can use pass:
def process_order():
pass
pass is a no-op statement; it does not execute any actual business logic.
It is commonly used for:
- Placeholders during development.
- Defining the interface first and supplementing the implementation later.
- Scenarios where certain syntax structures require a code block but currently have no content.
It should be noted that key business functions without implementations should not be retained long-term in production code.
III. Calling Functions
Defining a function does not execute the function body immediately.
The code inside the function only executes when the function is called.
1. Basic Call Syntax
function_name(arguments)
For example:
def say_hello():
print("Hello, Python!")
say_hello()
Output:
Hello, Python!
Where:
say_hellois the function name.()indicates a function call.- When called, the statements in the function body are executed.
2. Multiple Calls
The same function can be called repeatedly:
def welcome():
print("Welcome to Python")
welcome()
welcome()
welcome()
Output:
Welcome to Python
Welcome to Python
Welcome to Python
Each call executes the function body.
3. The Difference Between Definition and Calling
def greet():
print("Hello")
print("Function definition complete")
greet()
print("Function call complete")
Execution result:
Function definition complete
Hello
Function call complete
Function definition and function calling are two different stages:
- Definition stage: create the function object and bind the function name to that object.
- Calling stage: execute the code corresponding to the function object.
4. The Position of Function Definition
Typically, you need to define the function before calling it.
def greet():
print("Hello")
greet()
If you call it before the function name has been bound:
greet()
def greet():
print("Hello")
The program will raise a NameError.
This is because when execution reaches the first line, greet has not yet been bound in the current namespace.
A function definition statement is itself a statement executed at runtime, and is not automatically hoisted to the top of the program.
IV. Function Parameters
Function parameters (Parameter) are used to receive data passed by the caller.
Through parameters, the same function can process different inputs.
1. What Is a Formal Parameter
A formal parameter (Parameter) is a variable declared when the function is defined.
def greet(name):
print(f"Hello, {name}!")
Here, name is the formal parameter.
2. What Is an Actual Argument
An actual argument (Argument) is the specific value or expression passed when calling the function.
greet("Alice")
Here, "Alice" is the actual argument.
Output:
Hello, Alice!
The difference between formal parameters and actual arguments:
| Concept | Where It Appears | Example |
|---|---|---|
| Formal Parameter | Function definition | def greet(name) |
| Actual Argument | Function call | greet("Alice") |
3. One Parameter
def square(number):
result = number * number
print(result)
square(5)
square(8)
Output:
25
64
The function receives different numbers through its parameters and performs the same calculation logic.
4. Multiple parameters
A function can define multiple parameters.
def add(a, b):
result = a + b
print(result)
add(10, 20)
add(100, 200)
Output:
30
300
Multiple parameters are separated by commas.
5. Parameters and local variables
Parameters are bound to the corresponding parameter names when the function is called, and can be used inside the function body.
def calculate_total(price, quantity):
total = price * quantity
print(total)
calculate_total(100, 3)
Here:
priceis a parameter.quantityis a parameter.totalis a local variable defined inside the function.
V. Function return values
A return value is the result that a function hands back to the caller after execution.
Python uses the return statement to return data.
1. Using return to return a result
def add(a, b):
result = a + b
return result
total = add(10, 20)
print(total)
# 30
Execution process:
- Call
add(10, 20). - Parameter
areceives 10. - Parameter
breceives 20. - Calculate
a + b. - Use
returnto return the calculation result. - The call expression obtains the return value.
- Assign the return value to
total.
2. return ends function execution
def check_number(number):
if number > 0:
return "正数"
return "非正数"
result = check_number(10)
print(result)
# Positive number
When the function reaches return, the current function call ends immediately.
The statements after it will not continue to execute.
def test():
print("开始")
return "完成"
print("结束")
result = test()
Output:
开始
3. Functions without return
If a function does not explicitly execute return, Python implicitly returns None when the function ends normally.
def greet():
print("Hello")
result = greet()
print(result)
# None
4. No expression after return
Both of the following forms return None:
def first():
return
def second():
return None
Therefore:
print(first())
# None
print(second())
# None
5. Functions can return multiple values
Python supports separating multiple expressions with commas after return.
def calculate(a, b):
total = a + b
difference = a - b
return total, difference
result = calculate(20, 10)
print(result)
# (30, 10)
In fact, multiple return values are packed into a tuple.
You can receive them using sequence unpacking:
total, difference = calculate(20, 10)
print(total)
# 30
print(difference)
# 10
6. The difference between return values and print
This is a concept that Python beginners often confuse.
print() is responsible for displaying content to the output stream.
return is responsible for handing the result back to the function caller.
Example:
def add_with_print(a, b):
print(a + b)
def add_with_return(a, b):
return a + b
result1 = add_with_print(10, 20)
result2 = add_with_return(10, 20)
print(result1)
# None
print(result2)
# 30
The difference between the two:
| Comparison | return | |
|---|---|---|
| Main purpose | Output information | Return the computed result |
| Ends the function | No | Yes |
| Produces a result the caller can receive | Returns None | Returns the specified object |
| Can participate in subsequent calculations | The output cannot be used directly as the function result | Yes |
| Must appear inside a function | No | No |
For example:
def add(a, b):
return a + b
result = add(10, 20) * 2
print(result)
# 60
If print() is used instead of return, the caller cannot directly obtain the computed result.
6. Function Argument Passing
When a Python function is called, the arguments are bound to references to the passed-in objects.
Understanding this explains why modifying a list argument may affect external data, while rebinding the parameter name usually does not affect the caller's variable binding.
1. Passing Immutable Objects
def change_number(number):
number = 100
value = 10
change_number(value)
print(value)
# 10
Why does the external value not change?
Because number inside the function is only a local name.
Executing:
number = 100
It only rebinds the local name number to the integer object 100; it does not change the caller's name binding.
2. Passing Mutable Objects
def add_item(items):
items.append("Python")
languages = ["Java", "Go"]
add_item(languages)
print(languages)
# ['Java', 'Go', 'Python']
Why did the external list change?
Because the function parameter items and the external variable languages reference the same list object.
Calling append() modifies the shared object itself.
3. The Difference Between Rebinding and Modifying an Object
def modify_list(items):
items.append(100)
def rebind_list(items):
items = [100, 200]
numbers = [1, 2, 3]
modify_list(numbers)
print(numbers)
# [1, 2, 3, 100]
rebind_list(numbers)
print(numbers)
# [1, 2, 3, 100]
The difference between the two operations:
items.append(100): modifies the shared list object.items = [100, 200]: only changes the binding of the local name.
The argument-passing model commonly used in Python is called call by sharing (Call by Sharing); it can also be understood as passing object references by value.
Do not simply describe Python as pure pass-by-value or pure pass-by-reference in the traditional sense.
7. Function Argument Types
Python supports multiple argument forms, which can be flexibly combined according to the calling style and business requirements.
1. Positional Arguments
Positional arguments (Positional Argument) are matched according to their position in the definition.
def introduce(name, age):
print(f"姓名:{name}")
print(f"年龄:{age}")
introduce("Alice", 25)
Parameter matching relationship:
| Formal parameter | Actual argument |
|---|---|
name |
"Alice" |
age |
25 |
Pay attention to the argument order when calling.
2. Keyword Arguments
Keyword arguments (Keyword Argument) specify the passed value by parameter name.
```python def introduce(name, age): print(f"姓名:{name}") print(f"年龄:{age}") introduce(age=25, name="Alice") ```Keyword arguments don't need to be passed in the order given in the function definition.
Advantages:
- Better readability.
- Less chance of confusing what each argument means.
- Well suited to function calls with many parameters.
3. Default Parameters
Default parameters let you specify default values for parameters when defining a function.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet()
greet("Alice")
Output:
Hello, Guest!
Hello, Alice!
If the corresponding argument is not passed at call time, the default value is used.
Rules for Defining Default Parameters
Regular parameters must come before default parameters.
Correct:
def create_user(name, age=18):
print(name, age)
Incorrect:
def create_user(age=18, name):
print(name, age)
The latter will produce a syntax error.
The Mutable Default Argument Trap
Do not use mutable objects such as lists or dictionaries directly as default arguments.
Incorrect example:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("Python"))
print(add_item("Java"))
Result:
['Python']
['Python', 'Java']
Why does the second call retain the data from the first?
Because the default argument expression is evaluated when the function definition is executed, so the default list object is reused across multiple calls.
It is recommended to use None:
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("Python"))
# ['Python']
print(add_item("Java"))
# ['Java']
This way, a new list is created each time no list is passed in.
4. Variable Numbers of Positional Arguments
Using *args, you can accept a variable number of positional arguments.
def calculate_sum(*args):
print(args)
return sum(args)
print(calculate_sum(1, 2, 3))
print(calculate_sum(10, 20, 30, 40))
Inside the function, args is a tuple.
Example:
def show_items(*args):
for item in args:
print(item)
show_items("Python", "Java", "Go")
Applicable scenarios:
- When you don't know how many arguments the caller will pass.
- Implementing general-purpose utility functions.
- Writing functions for data aggregation and calculation.
5. Variable Numbers of Keyword Arguments
Using **kwargs, you can accept a variable number of keyword arguments.
def create_user(**kwargs):
print(kwargs)
create_user(
name="Alice",
age=25,
city="Tokyo"
)
Output:
{'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
Inside the function, kwargs is a dictionary.
You can iterate over these arguments:
def show_user(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
show_user(
name="Alice",
age=25
)
6. Comprehensive Example of Parameter Types
def create_order(
user_id,
product,
quantity=1,
*tags,
discount=0,
**extra
):
print("用户编号:", user_id)
print("商品:", product)
print("数量:", quantity)
print("标签:", tags)
print("折扣:", discount)
print("附加信息:", extra)
create_order(
1001,
"Keyboard",
2,
"electronics",
"office",
discount=10,
source="website"
)
This example involves:
user_id: an ordinary positional parameter.product: an ordinary positional parameter.quantity: a default parameter.*tags: a variable number of positional arguments.discount: a keyword-only parameter.**extra: a variable number of keyword arguments.
7. Summary of Parameter Types
| Parameter type | Syntax | Characteristics |
|---|---|---|
| Positional parameter | def f(a) |
Matched by position |
| Keyword argument | f(a=10) |
Matched by name |
| Default parameter | def f(a=10) |
Uses the default value when nothing is passed |
| Variable positional parameters | *args |
Accepts multiple positional arguments |
| Keyword-only parameter | def f(*, a) |
Must be passed by name |
| Variable keyword parameters | **kwargs |
Accepts multiple keyword arguments |
8. Unpacking and Passing Arguments
Python supports unpacking containers with * and ** when calling a function.
1. Unpacking a sequence with *
def add(a, b, c):
return a + b + c
numbers = [10, 20, 30]
result = add(*numbers)
print(result)
# 60
*numbers passes each element of the list as a separate positional argument.
2. Unpacking a dictionary with **
def introduce(name, age, city):
print(name, age, city)
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
introduce(**user)
The dictionary's keys need to match the names of the parameters that the function can accept.
3. Using * to collect the remaining arguments
def process(first, *others):
print("第一个:", first)
print("其他参数:", others)
process(10, 20, 30, 40)
Output:
第一个:10
其他参数:(20, 30, 40)
4. Using ** to collect the remaining keyword arguments
def create_user(name, **extra):
print("姓名:", name)
print("其他信息:", extra)
create_user(
"Alice",
age=25,
city="Tokyo"
)
5. Notes on unpacking arguments
*unpacks an iterable.**unpacks a key–value mapping, and the keys must be valid keyword-argument names.- After unpacking, the number of arguments passed must match the function signature.
- The same parameter must not be assigned a value more than once through different routes.
For example:
def greet(name):
print(name)
# TypeError: name got two values
greet("Alice", name="Bob")
9. Type Annotations for Parameters
Python supports type annotations (type hints) to describe the expected types of function parameters and return values.
1. Basic type annotations
```python def add(a: int, b: int) -> int: return a + b ```Where:
a: int: the expected type of parameter a is an integer.b: int: the expected type of parameter b is an integer.-> int: the function is expected to return an integer.
2. String Type Annotations
def greet(name: str) -> str:
return f"Hello, {name}"
3. Container Type Annotations
def calculate_total(numbers: list[int]) -> int:
return sum(numbers)
result = calculate_total([10, 20, 30])
For newer Python versions, you can use the built-in generic syntax directly, for example list[int].
4. Optional Types
When a function parameter or return value may be None, you can use a union type.
def find_user(user_id: int) -> str | None:
if user_id == 1:
return "Alice"
return None
In code that is compatible with older Python versions, you can also use Optional[str].
5. Type Annotations Do Not Automatically Enforce Type Checking
def add(a: int, b: int) -> int:
return a + b
print(add("Hello", "Python"))
# HelloPython
By default, Python does not automatically reject a function call just because the arguments passed in do not match the annotations.
Type annotations are mainly used to:
- Improve code readability.
- Support IDE autocompletion.
- Assist static type checking.
- Help developers understand function interfaces.
- Support documentation generation and code analysis.
You can use tools such as mypy and Pyright to perform static type checking.
10. Function Scope
Variables in functions have scope.
Scope determines where in the program a name can be accessed.
1. Local Variables
Variables defined inside a function are usually local variables.
def calculate():
result = 100
print(result)
calculate()
Outside the function, you usually cannot access that local variable directly:
def calculate():
result = 100
calculate()
# NameError
print(result)
2. Global Variables
Variables defined at the module level are usually global variables.
message = "Hello"
def greet():
print(message)
greet()
Functions can read external global variables.
3. The global Keyword
If you need to rebind a global variable inside a function, you can use global.
count = 0
def increment():
global count
count += 1
increment()
print(count)
# 1
Without a global declaration, assigning to a name inside a function usually makes it a local variable.
4. The nonlocal Keyword
nonlocal is used in a nested function to modify a variable in the nearest enclosing function scope.
def outer():
count = 0
def inner():
nonlocal count
count += 1
inner()
print(count)
outer()
# 1
nonlocal cannot be used to bind module-level global variables.
5. The LEGB Name Lookup Rule
The commonly used name lookup model in Python is LEGB:
| Level | Meaning | Description |
|---|---|---|
| L | Local | Current function's local scope |
| E | Enclosing | Enclosing function scope |
| G | Global | Module global scope |
| B | Built-in | Built-in namespace |
Example:
```python name = "Global" def outer(): name = "Enclosing" def inner(): name = "Local" print(name) inner() outer() # Local ```Inside a function, the current local scope is searched first.
Note that class scopes and nested function scopes have special rules for name lookup, so LEGB should not be understood as a simple model with no exceptions in every syntactic scenario.
11. The Execution Flow of a Function
A function call involves parameter binding, creation of an execution frame, execution of the function body, and returning the result.
1. The Function Definition Stage
def add(a, b):
return a + b
When the definition statement is executed, Python creates a function object and binds the name add to that object.
A function object contains information related to execution, such as:
- The function's code object.
- Default arguments.
- Keyword default arguments.
- A reference to the function's global namespace.
- Annotation information.
- Closure-related information (if any).
2. The Function Call Stage
result = add(10, 20)
Calling mainly involves:
- Evaluating the call expression.
- Obtaining the callable object.
- Evaluating the argument expressions.
- Binding the parameters.
- Creating or preparing the function's execution state.
- Executing the function body.
- Returning the result or propagating an exception.
- Restoring the caller's execution.
In CPython, a function call involves runtime mechanisms such as execution frames. The specific internal implementation evolves with Python versions, and the low-level details of any particular version should not be regarded as part of the Python language specification.