Python3 Functions
A function is an organized, reusable block of code used to implement a single, or related, functionality.
Functions improve application modularity and code reuse. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.
Defining a Function
Section titled “Defining a Function”You can define a function with the functionality you want. Here are the simple rules:
- The function code block begins with the def keyword, followed by the function identifier name and parentheses ().
- Any incoming parameters and arguments must be placed inside the parentheses, which can be used to define parameters.
- The first line of the function can optionally use a docstring — used to store the function description.
- The function content starts with a colon : and is indented.
- return [expression] ends the function, optionally returning a value to the caller. A return without an expression is equivalent to returning None.

Syntax
Section titled “Syntax”Python uses the def keyword to define a function. The general format is as follows:
By default, parameter values and parameter names are matched in the order declared in the function definition.
Example
Section titled “Example”Let’s use a function to output “Hello World!”:
A more complex application, with parameter variables in the function:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Compare two numbers and return the larger one:
Output of the above example:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Compute area function:
Output of the above example:
Function Calls
Section titled “Function Calls”Defining a function: gives the function a name, specifies the parameters contained in the function, and the code block structure.
After the basic structure of the function is completed, you can call it from another function, or directly from the Python command prompt.
The following example calls the printme() function:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
Parameter Passing
Section titled “Parameter Passing”In Python, types belong to objects, and objects have different types. Variables have no type:
In the above code, [1,2,3] is of type List, “Runoob” is of type String, and the variable a has no type — it is merely a reference (a pointer) to an object, which can point to a List type object or a String type object.
Mutable and Immutable Objects
Section titled “Mutable and Immutable Objects”In Python, strings, tuples, and numbers are immutable objects, while lists, dicts, and others are mutable objects.
-
Immutable types: Variable assignment a=5 followed by a=10 — this actually creates a new int value object 10, and then makes a point to it, while 5 is discarded. The value of a is not changed; rather, a is newly generated.
-
Mutable types: Variable assignment la=[1,2,3,4] followed by la[2]=5 — this changes the value of the third element of list la. la itself does not change; only a part of its internal value is modified.
Parameter passing in Python functions:
-
Immutable types: Similar to pass-by-value in C++, such as integers, strings, tuples. For example, fun(a) passes only the value of a, without affecting the a object itself. If you modify the value of a inside fun(a), a new object for a is generated.
-
Mutable types: Similar to pass-by-reference in C++, such as lists, dictionaries. For example, fun(la) actually passes la itself, so modifications inside fun will affect la outside.
In Python, everything is an object. Strictly speaking, we cannot say pass-by-value or pass-by-reference; we should say passing immutable objects and passing mutable objects.
Passing Immutable Objects Example
Section titled “Passing Immutable Objects Example”Use the id() function to see memory address changes:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
You can see that before and after calling the function, the formal parameter and the actual parameter point to the same object (same object id). After modifying the formal parameter inside the function, the formal parameter points to a different id.
Passing Mutable Objects Example
Section titled “Passing Mutable Objects Example”If a mutable object’s parameter is modified inside a function, the original parameter in the calling function is also changed. For example:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”The object passed into the function and the one with new content appended at the end use the same reference. Thus the output is:
Parameters
Section titled “Parameters”The following are the formal parameter types that can be used when calling a function:
- Required parameters
- Keyword parameters
- Default parameters
- Variable-length parameters
Required Parameters
Section titled “Required Parameters”Required parameters must be passed into the function in the correct order. The number of calls must be the same as in the declaration.
To call the printme() function, you must pass in one parameter; otherwise, a syntax error occurs:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
Keyword Parameters
Section titled “Keyword Parameters”Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the parameter values passed in.
Using keyword parameters allows the order of parameters in a function call to differ from the declaration, because the Python interpreter can match parameter values using parameter names.
The following example uses parameter names when calling the printme() function:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
The following example demonstrates that function parameters do not need to be used in the specified order:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
Default Parameters
Section titled “Default Parameters”When calling a function, if no parameter is passed, the default parameter is used. In the following example, if the age parameter is not passed in, the default value is used:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
Variable-Length Parameters
Section titled “Variable-Length Parameters”You may need a function that can handle more parameters than those declared initially. These parameters are called variable-length parameters. Unlike the two types above, they are not named when declared. The basic syntax is as follows:
Parameters with an asterisk * will be imported as a tuple, storing all unnamed variable parameters.
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
If no parameters are specified when calling the function, it becomes an empty tuple. We can also avoid passing unnamed variables to the function. As shown below:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
There is also a parameter with two asterisks **. The basic syntax is as follows:
Parameters with two asterisks ** will be imported as a dictionary.
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
When declaring a function, the asterisk * can appear alone in the parameter list, for example:
If the asterisk * appears alone, parameters after the asterisk * must be passed using keywords:
Anonymous Functions
Section titled “Anonymous Functions”Python uses lambda to create anonymous functions.
“Anonymous” means no longer using the standard def statement to define a function.
- lambda is just an expression; the function body is much simpler than def.
- The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in a lambda expression.
- lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace.
- Although lambda functions appear to be single-line, they are not equivalent to inline functions in C or C++. The purpose of inline functions is to avoid occupying stack memory when calling small functions, thereby reducing function call overhead and improving code execution speed.
Syntax
Section titled “Syntax”The syntax of a lambda function contains only one statement, as follows:
Set parameter a to add 10:
Example
Section titled “Example”Output of the above example:
The following example sets two parameters for an anonymous function:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
We can encapsulate anonymous functions within a function, allowing us to use the same code to create multiple anonymous functions.
The following example encapsulates an anonymous function within the myfunc function, creating different anonymous functions by passing different parameters:
Example
Section titled “Example”Output of the above example:
For more on anonymous functions, see: Python lambda (Anonymous Functions)
The return Statement
Section titled “The return Statement”The return [expression] statement is used to exit a function, optionally returning an expression to the caller. A return statement without a parameter value returns None. The previous examples did not demonstrate how to return a value. The following example demonstrates the usage of the return statement:
Example (Python 3.0+)
Section titled “Example (Python 3.0+)”Output of the above example:
Positional-Only Parameters
Section titled “Positional-Only Parameters”Python 3.8 introduced a new function parameter syntax / to indicate that certain function parameters must use positional arguments and cannot use keyword arguments.
In the following example, parameters a and b must use positional arguments, c or d can be positional or keyword arguments, and e and f must be keyword arguments:
The following usage is correct:
The following usage will cause errors: