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: passing the result 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 provided 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.
II. Formal Parameters and Actual Arguments
There are two easily confused concepts in Python functions: 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 reference 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 actual arguments to formal parameters according to the argument 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 for receiving data | Provides 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 can be correctly matched with the parameters in the function definition.
III. Classification of Python Function Parameters
Python supports multiple parameter forms, which can meet 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 is very important.
print(subtract(20, 5))
# 15
print(subtract(5, 20))
# -15
Swapping the positions of the parameters changes the calculation result.
2. Keyword Arguments
Keyword arguments specify the passed-in values by parameter name.
def introduce(name, age, city):
print(name, age, city)
introduce(
city="Tokyo",
name="Alice",
age=25
)
Keyword arguments do not need to be arranged according to their positions in the function definition.
Advantages:
- Improves code readability.
- Reduces the risk of argument-order errors.
- Suitable for functions with many 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")
Keep in mind:
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 can 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. Variable Number of Positional Arguments
Using *args allows a function to accept a variable 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.
Therefore, you can process this data using loops, indexing, and other tuple operations.
def show_items(*args):
for item in args:
print(item)
show_items("Python", "Java", "Go")
Use cases:
- A variable number of calculation arguments.
- General-purpose utility functions.
- Data aggregation.
- Decorators and function wrappers.
6. Variable Number of Keyword Arguments
Using **kwargs allows a function to 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 it using 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 before / can only be passed positionally.
def calculate(a, b, /):
return a + b
print(calculate(10, 20))
# 30
The following call will raise TypeError:
calculate(a=10, b=20)
This design is suitable for:
- APIs where callers should not rely on parameter names.
- Interfaces where parameter names need to be protected so the implementation can be adjusted in the future.
- Consistency with how certain built-in functions are called.
For example:
def process(value, /):
print(value)
process(100)
8. Keyword-Only Parameters
Using * marks the following parameters as passable only by keyword.
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")
because age and city are keyword-only parameters.
Keyword-only parameters are suitable for functions with multiple optional configuration items, making the intent of the call clearer.
9. Comprehensive Comparison of Parameter Types
| Parameter Type | Syntax | Passing Method |
|---|---|---|
| Positional parameters | def f(a) |
By position |
| Keyword arguments | f(a=10) |
By name |
| Default parameters | def f(a=10) |
Can be omitted |
| Variable positional parameters | *args |
Accepts multiple positional arguments |
| Positional-only parameters | / |
Can only be passed by position |
| Keyword-only parameters | * |
Can only be passed by name |
| Variable keyword parameters | **kwargs |
Accepts multiple keyword arguments |
IV. Argument Binding and Calling Rules
Argument binding is an important part of the function call process.
Python needs to establish a correspondence between actual arguments and formal parameters based on the function signature.
1. Basic Parameter Binding
def register(name, age):
print(name, age)
register("Alice", 25)
Binding relationship:
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 Multiple Times
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 Arguments
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 Argument Binding Errors
| Error type | Cause |
|---|---|
| Missing required argument | A required argument is missing |
| Too many positional arguments | Too many positional arguments |
| Unexpected keyword argument | The keyword name does not match |
| Multiple values for argument | The same argument is assigned a value more than once |
| Positional argument follows keyword argument | A positional argument appears after a keyword argument |
V. A Deeper Understanding of Default Arguments
Default arguments look simple, but they involve a very important mechanism: default values are evaluated when the function definition is executed, not re-evaluated on every call.
1. When Default Arguments Are Evaluated
def greet(name="Guest"):
print(name)
When the def statement is executed, the default value "Guest" is already fixed.
You can inspect the default values of positional arguments through __defaults__:
print(greet.__defaults__)
# ('Guest',)
2. The Mutable Default Argument Trap
An 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 call?
Because the list is created when the function is defined.
When items is not passed in on subsequent calls, the function keeps using 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 Argument Problem
The 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 Arguments
Default arguments can also be immutable objects, function objects, and other objects suitable for reuse.
def calculate(value, multiplier=2):
return value * multiplier
But keep the following in mind:
- Default values are evaluated only when the function is defined.
- Default argument objects may be shared across multiple calls.
- Mutable default arguments easily produce unexpected state.
- If you need to generate a default value dynamically, do so inside the function body.
- Do not rely on modifying
__defaults__to control business behavior.
VI. How Arguments Are Passed
Python's argument passing is often described as either pass-by-value or pass-by-reference, but neither traditional description fully captures Python's actual semantics.
A more accurate understanding is this: function parameters receive a reference binding to the object passed in, and the caller and the callee can refer to the same object under different names.
This model is usually called 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.
But executing:
number = 100
merely rebinds the local name number to a different 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() modified this shared list, so the change is observable externally as well.
3. Mutating 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 kinds of operations are fundamentally different:
| Operation | Behavior | External Effect |
|---|---|---|
items.append(100) |
Mutates the shared object | Visible externally |
items.clear() |
Mutates the shared object | Visible externally |
items = [100, 200] |
Rebinds the local name | Does not change the outer binding |
items = None |
Rebinds the local name | Does not change the outer binding |
4. Argument Passing Flowchart
flowchart TD
A["Call the function"] --> B["Evaluate the actual arguments"]
B --> C["Bind the parameter names to the passed objects"]
C --> D{"How does the function operate on the parameter?"}
D -->|"Mutate the object"| E["Change the shared object's state"]
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 is not supposed to change the data supplied by the caller, the object can be copied according to 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, and the inner objects may still be shared.
When nested mutable objects need to be fully isolated, consider copy.deepcopy(), but you must evaluate the object types, resources, and copying cost.
VII. Argument Unpacking and Passing
Python supports using * and ** to unpack sequences 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.
Tuples can be unpacked as well:
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 approach is commonly used in:
- Generic function wrappers.
- Decorators.
- API argument forwarding.
- Function calls inside frameworks.
4. The Difference Between Unpacking Arguments and Collecting Arguments
Note that the asterisks in function definitions and function calls have different meanings.
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 that a function hands back to the caller after execution.
Python uses the return statement to return objects.
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 number
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:
开始
3. Returning None When There Is No return
If a function does not execute an explicit return, it implicitly returns None when it finishes normally.
def greet():
print("Hello")
result = greet()
print(result)
# None
The following two forms return the same result:
def first():
return
def second():
return None
4. The 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 |
| Whether it ends the function | No | Yes |
| Whether it can be used directly as a computed result | No | Yes |
| Whether it changes 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 instead of only printing them.
5. Functions can return multiple values
In Python, you can use commas after return to separate multiple expressions.
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 the 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. Types and Design of Return Values
Return values are not only the result of a function's computation but also an important part of function interface design.
1. Returning a single basic 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 branching.
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 a collection of data with a variable number of items and meaningful order.
4. Returning a dictionary
def get_product():
return {
"id": 1001,
"name": "Keyboard",
"price": 199.9
}
Suitable for structured data with many fields.
5. Returning None Indicates 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 non-existence, no result, or no data provided.
Callers need to handle this case explicitly:
user = find_user(100)
if user is None:
print("用户不存在")
else:
print(user)
Using is None for this 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 | Meaning example |
|---|---|
None |
No result or not provided |
[] |
A list result, but currently has no elements |
{} |
A dictionary result, but currently has 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 | Basic data type |
| Success/failure determination | bool or a clear 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 casually return integers, strings, lists, and None in different situations without explaining what each of these results represents.
10. The 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 the error through an exception.
The choice between these two approaches should be based on business semantics.
1. Using 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. Using 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 |
|---|---|---|
| Main purpose | Express normal results or expected states | Express exceptional situations |
| Control flow | Return normally to the caller | Propagate up the call stack |
| Caller handling | Check the return result | Use try/except |
| Suitable scenarios | No query result, status checks | Invalid arguments, unavailable resources, etc. |
For example:
- When a queried user does not exist, you can return
Noneaccording to the API convention. - If the user input format is invalid, you can raise
ValueError. - If a file does not exist, you can let
FileNotFoundErrorpropagate or handle it at an appropriate layer. - If a network connection fails, you can raise the corresponding network exception.
What matters is that callers can accurately understand the function's behavior.
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: The parameter a is expected to be an integer.b: int: The 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 for Dynamic Typing
from typing import Any
def process_data(value: Any) -> Any:
return value
Any indicates 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 overused in all functions; otherwise, the value of type annotations will be reduced.
8. Using Callable to Describe Function Parameters
If a function accepts another function as a parameter, you can describe it using Callable.
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 Perform Type Conversion
def add(a: int, b: int) -> int:
return a + b
print(add("Hello", "Python"))
# HelloPython
By default, Python will not automatically reject a call just because the actual arguments do not match the annotations.
Type annotations mainly serve the following purposes:
- IDE autocompletion.
- Static type checking.
- Code documentation.
- Interface design.
- Code maintenance.