Appearance
Defining Functions
In Python, defining a function requires using the def
statement, followed by the function name, parentheses, parameters within the parentheses, and a colon :
. Then, within the indented block, you write the function body. The function's return value is returned using the return
statement.
Let's take defining a custom absolute value function my_abs
as an example:
python
def my_abs(x):
if x >= 0:
return x
else:
return -x
print(my_abs(-99))
Please test and call my_abs
yourself to see if the return result is correct.
Note: Once a return
statement is executed within the function body, the function execution is completed, and the result is returned. Therefore, conditional statements and loops inside the function can implement very complex logic.
If there is no return
statement, the function will still return a result after execution, but the result will be None
. return None
can be abbreviated as return
.
When defining a function in the Python interactive environment, note that Python will display the ...
prompt. After the function definition is complete, press Enter
twice to return to the >>>
prompt:
┌────────────────────────────────────────────────────────┐
│Command Prompt - python - □ x │
├────────────────────────────────────────────────────────┤
│>>> def my_abs(x): │
│... if x >= 0: │
│... return x │
│... else: │
│... return -x │
│... │
│>>> my_abs(-9) │
│9 │
│>>> _ │
│ │
└────────────────────────────────────────────────────────┘
If you have already saved the my_abs()
function definition in a file named abstest.py
, you can start the Python interpreter in the current directory of that file and import the my_abs()
function using from abstest import my_abs
. Note that abstest
is the filename (without the .py
extension):
┌────────────────────────────────────────────────────────┐
│Command Prompt - python - □ x │
├────────────────────────────────────────────────────────┤
│>>> from abstest import my_abs │
│>>> my_abs(-9) │
│9 │
│>>> _ │
│ │
│ │
└────────────────────────────────────────────────────────┘
The usage of import
will be explained in detail in the following modules.
Empty Functions
If you want to define an empty function that does nothing, you can use the pass
statement:
python
def nop():
pass
The pass
statement does nothing, but what is its use? In fact, pass
can be used as a placeholder. For example, if you haven't decided how to write the function's code yet, you can place a pass
to allow the code to run.
pass
can also be used in other statements, such as:
python
if age >= 18:
pass
Without pass
, the code would result in a syntax error.
Parameter Checking
When calling a function, if the number of parameters is incorrect, the Python interpreter will automatically detect it and raise a TypeError
:
python
>>> my_abs(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_abs() takes 1 positional argument but 2 were given
However, if the parameter types are incorrect, the Python interpreter cannot check it for us. Let's compare the differences between my_abs
and the built-in abs
function:
python
>>> my_abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in my_abs
TypeError: unorderable types: str() >= int()
>>> abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'
When inappropriate parameter types are passed, the built-in abs
function can detect the parameter error, but our custom my_abs
does not perform parameter checking. This leads to the if
statement causing an error, and the error message differs from that of abs
. Therefore, this function definition is not sufficiently robust.
Let's modify the definition of my_abs
to perform parameter type checking, only allowing integer and float types as parameters. Data type checking can be implemented using the built-in isinstance()
function:
python
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError('bad operand type')
if x >= 0:
return x
else:
return -x
After adding parameter checking, if an incorrect parameter type is passed, the function can raise an error:
python
>>> my_abs('A')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in my_abs
TypeError: bad operand type
Error and exception handling will be discussed in subsequent sections.
Returning Multiple Values
Can a function return multiple values? The answer is yes.
For example, in games, it's often necessary to move from one point to another. Given coordinates, displacement, and angle, you can calculate the new coordinates:
python
import math
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
The statement import math
imports the math package, allowing subsequent code to reference functions like sin
and cos
from the math package.
Then, you can obtain the return values simultaneously:
python
>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print(x, y)
151.96152422706632 70.0
However, this is actually an illusion. Python functions still return a single value:
python
>>> r = move(100, 100, 60, math.pi / 6)
>>> print(r)
(151.96152422706632, 70.0)
The return value is a tuple! However, in syntax, returning a tuple can omit the parentheses, and multiple variables can receive a tuple simultaneously, assigning values by position. Therefore, returning multiple values in Python functions is essentially returning a tuple, but it is more convenient to write.
Summary
- When defining a function, you need to determine the function name and the number of parameters.
- If necessary, perform data type checks on the parameters.
- Within the function body, you can use
return
to return the function result at any time. - If a function completes execution without a
return
statement, it automatically returnsNone
. - A function can return multiple values simultaneously, which is essentially returning a tuple.