I. Overview of Function Parameters and Return Values
Functions are the basic unit in Python for organizing code and encapsulating business logic. A complete function usually revolves around three core parts:
- Input: receiving external data through parameters.
- Processing: performing calculations or business logic inside the function.
- Output: handing the result back to the caller through the return value.
For example:
def calculate_total(price, quantity):
total = price * quantity
return total
result = calculate_total(100, 3)
print(result)
# 300
In this example:
| Component | Content | Role |
|---|---|---|
| Function name | calculate_total |
Identifies the function |
| Formal parameters | price, quantity |
Receive input |
| Function body | price * quantity |
Performs the business calculation |
| Return value | total |
Outputs the calculation result |
| Actual arguments | 100, 3 |
Data supplied at call time |
Function parameters and return values together form the function interface.
The caller does not need to understand the specific implementation inside the function; they only need to know what data should be passed in and what result they can get back.
II. Formal Parameters and Actual Arguments
Python functions involve two concepts that are easy to confuse: formal parameters and actual arguments.
1. Formal Parameter
A formal parameter is a variable declared when the function is defined, used to receive the data passed in by the caller.
def greet(name):
print(f"你好,{name}!")
Here, name is the formal parameter.
It is essentially the name used inside the function to refer to the passed-in object.
2. Actual Argument
An actual argument is the concrete value or expression provided when calling the function.
greet("Alice")
Here, "Alice" is the actual argument.
When the function is called, Python binds the actual arguments to the formal parameters according to the parameter matching rules.
3. Differences Between Formal Parameters and Actual Arguments
| Comparison | Formal Parameter | Actual Argument |
|---|---|---|
| English | Parameter | Argument |
| Where it appears | Function definition | Function call |
| Role | Declares the name that receives data | Provides the concrete data |
| Example | def add(a, b) |
add(10, 20) |
4. A Function Can Define Multiple Parameters
def introduce(name, age, city):
print(f"姓名:{name}")
print(f"年龄:{age}")
print(f"城市:{city}")
introduce("Alice", 25, "Tokyo")
Output:
姓名:Alice
年龄:25
城市:Tokyo
Parameters are separated by commas.
When calling, you need to ensure that the actual arguments match the parameters in the function definition correctly.
III. Parameter Categories in Python Functions
Python supports several parameter forms, which can satisfy different function call requirements.
1. Positional Parameters
Positional parameters are matched according to their position in the function definition.
def subtract(a, b):
return a - b
result = subtract(20, 5)
print(result)
# 15
Matching relationship:
| Formal Parameter | Actual Argument |
|---|---|
a |
20 |
b |
5 |
The order of positional parameters matters a great deal.
print(subtract(20, 5))
# 15
print(subtract(5, 20))
# -15
Swapping the positions of the arguments changes the calculation result.
2. Keyword Arguments
Keyword arguments specify the passed-in values by parameter name.
```python def introduce(name, age, city): print(name, age, city) introduce( city="Tokyo", name="Alice", age=25 ) ```Keyword arguments do not need to be arranged in the order they appear in the function definition.
Advantages:
- Improves code readability.
- Reduces the risk of getting the argument order wrong.
- Well suited to functions with a large number of parameters.
- Makes the business meaning of each parameter explicit.
3. Mixing Positional and Keyword Arguments
Python allows positional and keyword arguments to be mixed in a single call.
def create_user(name, age, city):
print(name, age, city)
create_user("Alice", age=25, city="Tokyo")
Note the following:
Positional arguments must come before keyword arguments.
Correct:
create_user("Alice", age=25, city="Tokyo")
Incorrect:
# SyntaxError
create_user(name="Alice", 25, city="Tokyo")
Because positional arguments cannot appear after keyword arguments.
4. Default Parameters
A default parameter is a parameter whose default value is specified when the function is defined.
If the caller does not provide that argument, the function uses the default value.
def greet(name="Guest"):
print(f"Hello, {name}!")
greet()
# Hello, Guest!
greet("Alice")
# Hello, Alice!
Default parameters make function calls more flexible.
Rules for Defining Default Parameters
Regular required parameters should come before default parameters.
Correct:
def create_user(name, age=18):
print(name, age)
Incorrect:
# SyntaxError
def create_user(age=18, name):
print(name, age)
5. A Variable Number of Positional Arguments
Using *args lets a function accept an arbitrary number of positional arguments.
def calculate_sum(*args):
print(args)
return sum(args)
print(calculate_sum(1, 2, 3))
# 6
print(calculate_sum(10, 20, 30, 40))
# 100
Inside the function, args is a tuple.
So you can process that data with loops, indexing, and other tuple operations.
def show_items(*args):
for item in args:
print(item)
show_items("Python", "Java", "Go")
Use cases:
- Computations with a variable number of arguments.
- General-purpose utility functions.
- Data aggregation.
- Decorators and function wrappers.
6. A Variable Number of Keyword Arguments
Using **kwargs lets a function receive an arbitrary 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 it with items():
def show_user(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
show_user(
name="Alice",
age=25,
city="Tokyo"
)
7. Positional-Only Parameters
Python 3.8 introduced positional-only parameter syntax, marked with /.
Parameters placed before / can only be passed by position.
def calculate(a, b, /):
return a + b
print(calculate(10, 20))
# 30
The following call raises TypeError:
calculate(a=10, b=20)
This design is suitable when:
- Callers should not rely on parameter names in an API.
- Parameter names need to be protected so the implementation can be adjusted in the future.
- The calling convention needs to stay consistent with certain built-in functions.
For example:
def process(value, /):
print(value)
process(100)
8. Keyword-only parameters
Using * marks the following parameters as keyword-only.
def create_user(name, *, age, city):
print(name, age, city)
create_user(
"Alice",
age=25,
city="Tokyo"
)
The following call is invalid:
create_user("Alice", 25, "Tokyo")
This is because age and city are keyword-only parameters.
Keyword-only parameters are suitable for functions with multiple optional configuration items, and they make the intent of the call clearer.
9. Comprehensive Comparison of Parameter Types
| Parameter Type | Syntax | Passing Method |
|---|---|---|
| Positional parameter | def f(a) |
By position |
| Keyword parameter | f(a=10) |
By name |
| Default parameter | def f(a=10) |
Can be omitted |
| Variable positional parameter | *args |
Accepts multiple positional arguments |
| Positional-only parameter | / |
Can only be passed by position |
| Keyword-only parameter | * |
Can only be passed by name |
| Variable keyword parameter | **kwargs |
Accepts multiple keyword arguments |
IV. Parameter Binding and Calling Rules
Argument binding is an important part of the function call process.
Python needs to map actual arguments to formal parameters based on the function signature.
1. Basic Parameter Binding
def register(name, age):
print(name, age)
register("Alice", 25)
Binding relationships:
name = "Alice"
age = 25
2. Positional Arguments Are Matched First
def show_info(name, age, city):
print(name, age, city)
show_info("Alice", 25, city="Tokyo")
Python first matches by position:
name = "Alice"
age = 25
The remaining city is matched by keyword.
3. The Same Parameter Cannot Be Assigned Twice
def greet(name):
print(name)
# TypeError
greet("Alice", name="Bob")
Here name already receives a value through a positional argument and then receives a second value through a keyword argument, resulting in an argument binding error.
4. Missing Required Parameter
def add(a, b):
return a + b
# TypeError
add(10)
Parameter b is not assigned a value.
5. Extra Arguments
def greet(name):
print(name)
# TypeError
greet("Alice", "Bob")
The function accepts only one positional argument, but two are passed.
6. Common Types of Parameter Binding Errors
| Error Type | Cause |
|---|---|
| Missing required argument | A required argument is missing |
| Too many positional arguments | More positional arguments than expected |
| Unexpected keyword argument | Keyword name does not match |
| Multiple values for argument | The same argument is assigned multiple times |
| Positional argument follows keyword argument | A positional argument appears after a keyword argument |
V. In-Depth Understanding of Default Parameters
Default parameters may seem simple, but there is a very important mechanism behind them: default values are evaluated when the function definition is executed, not re-evaluated on every call.
1. Evaluation Timing of Default Parameters
def greet(name="Guest"):
print(name)
When the def statement is executed, the default value "Guest" is already fixed.
You can use __defaults__ to inspect the default values for positional parameters:
print(greet.__defaults__)
# ('Guest',)
2. The Mutable Default Parameter Trap
Incorrect example:
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("Python"))
# ['Python']
print(add_item("Java"))
# ['Python', 'Java']
Why does the second call still retain the data from the first?
Because the list is created when the function is defined.
When items is not passed in on subsequent calls, the function continues to use the same default list object.
You can observe this as follows:
def collect(item, items=[]):
items.append(item)
return items
print(collect.__defaults__)
3. Using None to Solve the Mutable Default Parameter Problem
Recommended approach:
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']
On each call, if no list is passed in, a new list is created inside the function.
4. Other Considerations When Using Default Parameters
Default parameters can also be immutable objects, function objects, and other objects suitable for reuse.
def calculate(value, multiplier=2):
return value * multiplier
However, note the following:
- Default values are evaluated only when the function is defined.
- The default parameter object may be shared across multiple calls.
- Mutable default parameters can easily lead to unexpected state.
- If a default value needs to be generated dynamically, it should be done inside the function body.
- Do not rely on modifying
__defaults__to control application behavior.
VI. Parameter Passing Mechanism
Python's parameter passing is often described as pass-by-value or pass-by-reference, but neither traditional term fully captures Python's actual semantics.
A more accurate understanding is this: function parameters receive reference bindings to the objects passed in, and the caller and callee can refer to the same object through different names.
This model is commonly referred to as shared-object passing (call by sharing).
1. Passing in an Immutable Object
def change_number(number):
number = 100
value = 10
change_number(value)
print(value)
# 10
Inside the function, number and the outer value initially reference the same integer object.
However, executing:
number = 100
only rebinds the local name number to another integer object.
It does not change the binding of the outer name value.
2. Passing in a Mutable Object
def add_item(items):
items.append("Python")
languages = ["Java", "Go"]
add_item(languages)
print(languages)
# ['Java', 'Go', 'Python']
Here, the parameter items and the outer variable languages reference the same list object.
Calling append() modifies this shared list, so the change is also observable from the outside.
3. Modifying Objects vs. Rebinding Names
def modify(items):
items.append(100)
def rebind(items):
items = [100, 200]
numbers = [1, 2, 3]
modify(numbers)
print(numbers)
# [1, 2, 3, 100]
rebind(numbers)
print(numbers)
# [1, 2, 3, 100]
The two operations are fundamentally different:
| Operation | Behavior | External effect |
|---|---|---|
items.append(100) |
Modifies the shared object | Visible externally |
items.clear() |
Modifies the shared object | Visible externally |
items = [100, 200] |
Rebinds the local name | Does not change the external binding |
items = None |
Rebinds the local name | Does not change the external binding |
4. Parameter Passing Flowchart
flowchart TD
A["Call the function"] --> B["Evaluate the actual arguments"]
B --> C["Bind parameter names to the passed-in objects"]
C --> D{"How does the function operate on the parameter?"}
D -->|"Modify the object"| E["Change the state of the shared object"]
D -->|"Rebind the name"| F["Change the local name binding"]
E --> G["The caller can observe the object change"]
F --> H["The caller's original binding stays unchanged"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
5. How to Avoid Accidentally Modifying External Data
If a function should not change the data provided by the caller, you can copy the object according to your actual needs.
Shallow copy:
def process_items(items):
copied = items.copy()
copied.append(100)
return copied
For nested structures, a shallow copy only copies the outer container; the inner objects may still be shared.
When you need to fully isolate nested mutable objects, consider copy.deepcopy(), but you must evaluate the object types, resources, and copy cost.
7. Argument Unpacking and Passing
Python supports using * and ** to unpack sequence and mapping objects at function call time.
1. Unpacking Sequences 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.
You can also unpack tuples:
values = (10, 20, 30)
print(add(*values))
# 60
2. Unpacking Dictionaries with **
def introduce(name, age, city):
print(name, age, city)
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
introduce(**user)
The keys in the dictionary become the keyword argument names, and the values become the actual values of the corresponding parameters.
3. Using * and ** Together
def create_user(name, age, city, role):
print(name, age, city, role)
args = ("Alice", 25)
kwargs = {
"city": "Tokyo",
"role": "Developer"
}
create_user(*args, **kwargs)
This pattern is commonly used in:
- Generic function wrappers.
- Decorators.
- API argument forwarding.
- Function calls inside frameworks.
4. Difference Between Unpacking Arguments and Collecting Arguments
Note that the asterisk has different meanings in function definitions and function calls.
Function definition:
def process(*args, **kwargs):
print(args)
print(kwargs)
Here, *args and **kwargs are used to collect arguments.
Function call:
values = [1, 2, 3]
options = {"name": "Alice"}
process(*values, **options)
Here, * and ** are used to unpack arguments.
5. Common Errors When Unpacking
Argument count mismatch
def add(a, b):
return a + b
numbers = [1, 2, 3]
# TypeError
add(*numbers)
Dictionary keys do not match function parameters
def greet(name):
print(name)
user = {"username": "Alice"}
# TypeError
greet(**user)
The same argument is passed more than once
def greet(name):
print(name)
# TypeError
greet("Alice", **{"name": "Bob"})
VIII. Function Return Values
A return value is the result a function hands back to the caller after execution.
Python uses the return statement to return an object.
1. Basic Syntax of return
def function_name():
return expression
For example:
def add(a, b):
return a + b
result = add(10, 20)
print(result)
# 30
The return value can be any Python object, including:
- Integers.
- Floating-point numbers.
- Strings.
- Booleans.
- Lists.
- Tuples.
- Dictionaries.
- Sets.
- Function objects.
- Custom objects.
- Generator objects.
2. return Ends the Current Function Call
def check_number(number):
if number > 0:
return "正数"
return "非正数"
print(check_number(10))
# Positive
After the function reaches return, the current call ends immediately.
The statements after it will not continue to execute.
def test():
print("开始")
return "完成"
print("结束")
test()
Output:
Start
3. Returns None When There Is No return
If a function does not execute an explicit return, it implicitly returns None when it ends normally.
def greet():
print("Hello")
result = greet()
print(result)
# None
The following two forms have the same return result:
def first():
return
def second():
return None
4. Difference Between return and print
print() is used to output content, while return is used to return a result.
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
Comparison:
| Aspect | return | |
|---|---|---|
| Core purpose | Display content | Return an object |
| Does it end the function? | No | Yes |
| Can it be used directly as a computation result? | No | Yes |
| Does it change the caller's variable binding? | No | The caller decides how to use the result |
| Main use | Debugging and output | Passing function results |
In engineering practice, business calculation functions should usually return results rather than only print them.
5. Functions Can Return Multiple Values
Python can use commas to separate multiple expressions 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.
Therefore, they can be received using sequence unpacking:
total, difference = calculate(20, 10)
print(total)
# 30
print(difference)
# 10
You can also receive only part of them:
total, _ = calculate(20, 10)
print(total)
# 30
Here, _ is just a common placeholder name, not special ignore syntax.
6. Conditional Returns
A function can return different results based on different conditions.
def get_grade(score):
if score >= 90:
return "优秀"
if score >= 80:
return "良好"
if score >= 60:
return "及格"
return "不及格"
Using return in conditional branches allows a function to end early when a condition is met.
7. Returning Container Objects
A function can organize multiple related pieces of data into a dictionary and return it.
def get_user():
return {
"id": 1001,
"name": "Alice",
"age": 25
}
user = get_user()
print(user["name"])
# Alice
Returning a dictionary is suitable for results with many fields and clear names.
If the result structure is fixed, you can also consider using dataclass or NamedTuple.
8. Returning Function Objects
In Python, functions are also objects, so a function can be the return value of another function.
def get_operation():
def add(a, b):
return a + b
return add
operation = get_operation()
print(operation(10, 20))
# 30
This mechanism is the foundation of advanced features such as closures, higher-order functions, and decorators.
IX. Return Value Types and Design
The return value is not only the result of a function's computation but also an important part of function interface design.
1. Returning a Single Primitive Data Type
def get_age():
return 25
age = get_age()
Suitable for returning a single, clear result.
2. Returning a Boolean Value
def is_adult(age):
return age >= 18
print(is_adult(20))
# True
Such functions are usually used for judgments, validation, and conditional branches.
For naming, you can use prefixes such as is_, has_, and can_.
3. Returning a List
def get_active_users():
return ["Alice", "Bob", "Charlie"]
users = get_active_users()
Suitable for returning data collections whose size is not fixed and whose order is meaningful.
4. Returning a Dictionary
def get_product():
return {
"id": 1001,
"name": "Keyboard",
"price": 199.9
}
Suitable for structured data with many return fields.
5. Return None to indicate no result
def find_user(user_id):
if user_id == 1:
return "Alice"
return None
user = find_user(100)
None is often used to indicate nonexistence, no result, or no data provided.
The caller needs to handle this situation explicitly:
user = find_user(100)
if user is None:
print("用户不存在")
else:
print(user)
Using is None for the check is usually more appropriate than == None.
6. Do not confuse None with empty containers
The following results have different meanings:
def return_none():
return None
def return_empty_list():
return []
def return_empty_dict():
return {}
def return_empty_string():
return ""
| Return value | Example meaning |
|---|---|
None |
No result or not provided |
[] |
There is a list result, but currently no elements |
{} |
There is a dictionary result, but currently no fields |
"" |
An empty string was returned |
The function interface should clearly define the business meaning of these values.
7. Principles for choosing return values
| Business requirement | Recommended return value |
|---|---|
| Single calculation result | Primitive data type |
| Success or failure determination | bool or an explicit result object |
| Multiple elements of the same type | list, tuple |
| Multiple named fields | dict, dataclass |
| No query result | None or an explicit empty result |
| Lazy data stream | Generator or iterator |
| Multiple business outcomes | Structured result object or exception mechanism |
Do not, just to save effort, let a function arbitrarily return integers, strings, lists, and None in different situations without explaining what each result represents.
10. Difference Between Return Values and Exceptions
When a function cannot complete its task normally, it can express the result through a return value or express an error through an exception.
The choice between these two approaches should be based on business semantics.
1. Use return values to represent normal results
def divide(a, b):
if b == 0:
return None
return a / b
The caller needs to check the result:
result = divide(10, 0)
if result is None:
print("无法计算")
else:
print(result)
2. Use exceptions to express errors
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
Call:
try:
result = divide(10, 0)
except ValueError as exc:
print("计算失败:", exc)
3. Comparison of return values and exceptions
| Comparison | Return value | Exception |
|---|---|---|
| Primary use | Express normal results or expected states | Express exceptional situations |
| Control flow | Returns normally to the caller | Propagates up the call stack |
| Caller handling | Check the return result | Use try/except |
| Suitable scenarios | Query with no result, status checks | Invalid arguments, unavailable resources, etc. |
For example:
- If the queried user does not exist, you can return
Noneaccording to the API contract. - If the user input format is invalid, you can raise
ValueError. - If the file does not exist, you can let
FileNotFoundErrorpropagate or handle it at an appropriate layer. - If the network connection fails, you can raise the corresponding network exception.
The important thing is to let callers understand the function's behavior accurately.
11. Type Annotations for Function Parameters and Return Values
Python supports describing the expected types of parameters and return values through type annotations.
1. Basic Syntax
def function_name(
parameter: ParameterType
) -> ReturnType:
return result
For example:
def add(a: int, b: int) -> int:
return a + b
Here:
a: int: parameter a is expected to be an integer.b: int: parameter b is expected to be an integer.-> int: the function is expected to return an integer.
2. String Parameters and Return Values
def greet(name: str) -> str:
return f"Hello, {name}"
3. List Parameters and Return Values
def get_positive_numbers(
numbers: list[int]
) -> list[int]:
return [
number
for number in numbers
if number > 0
]
4. Dictionary Parameters and Return Values
def get_user(
user_id: int
) -> dict[str, str | int]:
return {
"id": user_id,
"name": "Alice"
}
5. Union Types
If a parameter or return value may have multiple types, you can use a union type.
def normalize(value: int | float) -> float:
return float(value)
Starting with Python 3.10, | is supported to represent union types.
6. Optional Return Values
If a function may return the specified type or may return None, you can annotate it like this:
def find_user(user_id: int) -> str | None:
if user_id == 1:
return "Alice"
return None
In older versions, you can also use:
from typing import Optional
def find_user(user_id: int) -> Optional[str]:
if user_id == 1:
return "Alice"
return None
7. Using Any to Represent Dynamic Types
from typing import Any
def process_data(value: Any) -> Any:
return value
Any means that the type checker does not impose the usual static type constraints on that object.
It is suitable for handling dynamic data, but it should not be abused in all functions, otherwise the value of type annotations will be reduced.
8. Using Callable to Describe Function Parameters
If a function receives another function as a parameter, you can use Callable to describe it.
from collections.abc import Callable
def execute(
operation: Callable[[int, int], int],
a: int,
b: int
) -> int:
return operation(a, b)
def add(a: int, b: int) -> int:
return a + b
print(execute(add, 10, 20))
# 30
9. Type Annotations Do Not Automatically Enforce Conversion
def add(a: int, b: int) -> int:
return a + b
print(add("Hello", "Python"))
# HelloPython
By default, Python does not automatically reject a call just because the actual arguments do not match the annotations.
Type annotations mainly serve:
- IDE autocompletion.
- Static type checking.
- Code documentation.
- Interface design.
- Code maintenance.