In Python, to define a function, you use the def statement, followed by the function name, parentheses (), the parameters inside the parentheses, and a colon :. Then, the function body is written within an indented block, and the function’s return value is specified using the return statement.
Let’s take the example of defining our own my_abs function to calculate the absolute value:
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 returned result is correct.
Note that when the statements inside the function body are executed, once the return statement is reached, the function execution is completed, and the result is returned. Therefore, very complex logic can be implemented inside a function through conditional statements and loops.
If there is no return statement, the function will still return a result after execution, but that result will be None. return None can be abbreviated as just return.
When defining a function in the Python interactive environment, note that Python will display ... as a prompt. After finishing the function definition, you need to press Enter twice to return to the >>> prompt:
┌─────────────────────────────────────────────────────────┐
│Windows PowerShell - □ x │
├─────────────────────────────────────────────────────────┤
│>>> def my_abs(x): │
│... if x >= 0: │
│... return x │
│... else: │
│... return -x │
│... │
│>>> my_abs(-9) │
│9 │
│>>> │
│ │
└─────────────────────────────────────────────────────────┘
If you have saved the function definition of my_abs() 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):
┌─────────────────────────────────────────────────────────┐
│Windows PowerShell - □ x │
├─────────────────────────────────────────────────────────┤
│>>> from abstest import my_abs │
│>>> my_abs(-9) │
│9 │
│>>> │
│ │
└─────────────────────────────────────────────────────────┘
The usage of import will be explained in detail in a subsequent section on modules.
If you want to define an empty function that does nothing, you can use the pass statement:
def nop():
pass
The pass statement does nothing. What is its use? In fact, pass can be used as a placeholder. For example, if you haven’t figured out how to write the function’s code yet, you can place a pass there to allow the code to run.
pass can also be used in other statements, such as:
if age >= 18:
pass
Without pass, the code will throw a syntax error when run.
When calling a function, if the number of parameters is incorrect, the Python interpreter will automatically check for it and raise a TypeError:
>>> 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 type is incorrect, the Python interpreter cannot check for it automatically. Try the difference between my_abs and the built-in function abs:
>>> 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 an inappropriate parameter is passed, the built-in function abs will detect the parameter error, while our defined my_abs lacks parameter checking, causing an error in the if statement with a different error message than abs. Therefore, this function definition is not perfect.
Let’s modify the definition of my_abs to check the parameter type, allowing only integer and floating-point types. Data type checking can be implemented using the built-in function isinstance():
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 the parameter check, if an incorrect parameter type is passed, the function will raise an error:
>>> 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 covered in a later section.
Can a function return multiple values? The answer is yes.
For example, in a game, you often need to move from one point to another. Given the coordinates, displacement, and angle, you can calculate the new coordinates:
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 import math statement imports the math module, allowing subsequent code to reference functions like sin and cos within the math module.
Then, we can obtain the return values simultaneously:
>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print(x, y)
151.96152422706632 70.0
But in reality, this is just an illusion. A Python function still returns a single value:
>>> r = move(100, 100, 60, math.pi / 6)
>>> print(r)
(151.96152422706632, 70.0)
The returned value is actually a tuple! However, syntactically, returning a tuple allows omitting the parentheses, and multiple variables can receive a tuple simultaneously, assigning values according to their positions. Therefore, returning multiple values from a Python function is essentially returning a tuple, but it is written more conveniently.
When defining a function, you need to determine the function name and the number of parameters.
If necessary, you can first check the data types of the parameters.
The function body can use return to return the function result at any time.
If a function completes execution without a return statement, it automatically returns None.
A function can return multiple values simultaneously, but it is actually a single tuple.