Table of contents
5. Function documentation string
b. from module name import function name
2. Anonymous function (Lambda function)
I. Introduction
Python is a high-level programming language created by Guido van Rossum in 1991. It is known for its concise, easy-to-read syntax, powerful functionality, and wide range of applications. Python has a rich standard library and third-party libraries that can be used to develop various types of applications, including web development, data analysis, artificial intelligence, scientific computing, automation scripts, etc.
Python itself is a great general-purpose programming language and, with the help of some popular libraries (numpy, scipy, matplotlib), becomes a powerful environment for scientific computing. This series will introduce the Python programming language and methods of using Python for scientific computing, mainly including the following content:
- Python: basic data types, containers (lists, tuples, sets, dictionaries), functions, classes
- Numpy: arrays, array indexing, data types, array math, broadcasting
- Matplotlib: plots, subplots, images
- IPython: Creating notebooks, typical workflow
2. Experimental environment
numpy | 1.21.6 | |
python | 3.7.16 |
- Run the following command to check the Python version
python --version
- Run the following code to check the Python and NumPy versions
import sys
import numpy as np
print("Python 版本:", sys.version)
print("NumPy 版本:", np.__version__)
3. Basics of Python functions
A Python function refers to a reusable block of code that performs a specific task. Functions accept input parameters (optional) and return an output result (optional). Python functions have the following key features:
1. Define functions
Use keywords def
to define functions. Function definition includes function name, parameter list and function body.
def add_numbers(a, b):
sum = a + b
return sum
The above code defines a add_numbers
function called that takes two arguments a
and b
returns their sum.
2. Parameter passing
Functions can accept zero or more parameters. Parameters can be required (must be provided) or optional (can be omitted). Functions receive input values via parameters when called.
def greet(name):
print("Hello, " + name + "!")
The above code defines a greet
function named that takes a name
parameter named and prints out the greeting.
3. Function call
To call a function, you use the function name and the corresponding parameter list.
result = add_numbers(3, 4)
print(result)
The above code calls add_numbers
the function, assigns the returned result to result
a variable, and prints out the result.
4. Return value
Functions can use return
statements to return a value. The return value can be any type of object, such as numbers, strings, lists, etc.
def multiply_numbers(a, b):
product = a * b
return product
The above code defines a multiply_numbers
function named that takes two arguments a
and b
returns their product.
5. Function documentation string
In order to facilitate other developers to understand the purpose and use of the function, you can use documentation strings (docstring) for comments inside the function. The docstring is the string that follows the function definition and can be viewed through help()
the function or .__doc__
property.
def add_numbers(a, b):
"""
This function adds two numbers and returns the result.
"""
sum = a + b
return sum
help(add_numbers)
print(add_numbers.__doc__)
4. Store functions in modules
1. Create module
Create a new Python file and name it the desired module name (for example my_module.py
). In this file, define functions and other relevant code.
def add_numbers(a, b):
return a + b
def multiply_numbers(a, b):
return a * b
# 其他函数和代码...
Save the file and place it somewhere the Python interpreter can access it. Typically, you can place a module file in the same directory as the code file that calls it.
2. Import module
Storing functions in modules improves code organization and reusability. Modules are a way of encapsulating related functionality together so that they can be used in multiple files within a project and can be shared and reused with other developers.
a. import 模块名
In another Python script, import
import the created module by using the statement.
import my_module
result = my_module.add_numbers(3, 5)
print(result) # 输出:8
result = my_module.multiply_numbers(2, 4)
print(result) # 输出:8
Once a module is imported via import
a statement, functions and other code defined in the module can be used. There are 模块名.函数名
ways to call functions in modules.
b. from 模块名 import 函数名
In the used from 模块名 import 函数名
form, the function name can be called directly without using the module name as a prefix.
from my_module import add_numbers
result = add_numbers(3, 5)
print(result) # 输出:8
This way you can selectively import specific functions or variables in the module so that they can be used more conveniently.
c. from 模块名 import *
The method used from 模块名 import *
can import all functions and variables in the module. This import method imports all public (not starting with an underscore) functions and variables in the module into the current namespace.
However, it is recommended to avoid using from 模块名 import *
this method to import modules, especially in large projects. This is because this approach may lead to namespace pollution and naming conflicts. When there are multiple functions or variables in an imported module that have the same name as in the current namespace, naming conflicts can occur, leading to unpredictable behavior.
Instead, it is recommended to use the explicit import method, that is, use the form of from 模块名 import 函数名
or import 模块名
. This makes it clear which function or module to import, and when used it is clear where it comes from.
If you really need to import all the functions and variables in the module, you can import the entire module using , and call them import 模块名
when using . 模块名.函数名
This avoids naming conflicts and expresses the intent of the code more clearly.
5. Various forms of functions
1. Ordinary functions
Ordinary functions are the most common form of functions, def
defined by keywords, that can accept parameters and return a value.
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) # 输出:8
2. Anonymous function (Lambda function)
An anonymous function (lambda function) is a simple function form without a function name. It is usually used for simple functions that need to be defined and used once . Anonymous functions lambda
are defined using keywords and can contain one or more parameters and an expression as the function body. Here is an example of using an anonymous function to calculate the sum of two numbers:
add_numbers = lambda a, b: a + b
result = add_numbers(3, 5)
print(result) # 输出:8
3. Built-in functions
Python provides many built-in functions, which are predefined functions provided by the Python interpreter and can be used directly. These built-in functions include len()
, print()
, range()
, type()
etc. to perform various common operations. Here are some examples of commonly used built-in functions:
# 获取字符串长度
length = len("Hello, world!")
print(length) # 输出:13
# 打印文本
print("Hello, world!")
# 生成整数序列
numbers = list(range(1, 6))
print(numbers) # 输出:[1, 2, 3, 4, 5]
# 获取对象类型
print(type(numbers)) # 输出:<class 'list'>
4. Recursive functions
a. Recursive concept
Function recursion is the process by which a function calls itself within its body. A recursive function usually consists of two parts: the base case and the recursive case.
- The base case refers to the condition under which the function stops recursion. When the base case is met, the recursive function no longer calls itself, but returns a specific value or performs other operations.
- A recursive situation is a condition in which a function continues to call itself recursively. In the case of recursion, the function solves a smaller problem by passing different parameter values. By continuously reducing the size of the problem, the base case is finally reached, thus ending the recursion.
b. Recursive conditions
Recursive functions need to meet the following two important conditions:
-
Base Cases : One or more base cases must exist to terminate the recursion and return a specific value or perform a specific action.
-
Convergence : recursive calls must approach the base case. That is, in each recursive call, the size of the problem should be smaller than the previous recursive call, eventually reaching the base case.
If a recursive function does not define the base case correctly or fails to converge, it will lead to infinite recursion, eventually leading to stack overflow or program crash. Recursive functions can provide a concise and elegant solution in certain situations. However, the execution process of recursion consumes more memory and time than iteration (loop), so you need to pay attention to the problem size and performance when using recursion.
Here is a classic example of a recursive function that calculates the factorial of a positive integer:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print(result) # 输出:120
In the above code, n
the recursive function returns 1 as the base case when equal to 0. Otherwise, the recursive function computes the product n
of and factorial(n - 1)
as the recursive case.
5. Higher-order functions
A higher-order function is a form of function that can accept a function as an argument or return a function. In Python, functions are first-class citizens, so they can be passed around and manipulated like any other object. Higher-order functions can be used to implement operations such as function combination, filtering, and mapping. For example, map()
and filter()
are common higher-order functions used to map and filter iterables. Here is an example map()
using sum:filter()
numbers = [1, 2, 3, 4, 5]
# 使用map()函数将每个数平方
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) # 输出:[1, 4, 9, 16, 25]
# 使用filter()函数过滤出偶数
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 输出:[2, 4]
In the example above, map()
the function squares each number and uses it lambda x: x**2
as a mapping function. filter()
The function filters out even numbers and is used lambda x: x % 2 == 0
as the filter function.
6. Decorator function
- A decorator function is a special function used to modify the behavior or functionality of other functions.
- Decorator functions usually accept a function as input and return a new function as output.
- Decorator functions extend the behavior of a function by adding additional functionality without modifying the original function code.
- Here is a simple decorator function that prints logs before and after function calls:
def logger(func):
def wrapper(*args, **kwargs):
print("Calling function:", func.__name__)
result = func(*args, **kwargs)
print("Function", func.__name__, "finished execution")
return result
return wrapper
@logger
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result) # 输出:8
In the above example, logger
the decorator function accepts a function as input and returns a new function wrapper
. wrapper
The function prints log information before and after calling the decorated function.
7. Generator function
- Generator functions are special functions that can be used to define generators.
- A generator is a special kind of iterator that generates values on demand rather than all at once.
- Generator functions use
yield
keywords to define each element of the generator. - Each time the generator's
next()
function is called orfor
iterated using a loop, the generator function resumes execution from where it last paused and produces the next value. - This on-demand generation of values improves performance and saves memory.
- Here is a generator function that produces the Fibonacci sequence:
def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
fib = fibonacci_generator()
print(next(fib)) # 输出:0
print(next(fib)) # 输出:1
print(next(fib)) # 输出:1
print(next(fib)) # 输出:2
# ...
# 使用for循环打印斐波那契数列的前十个数
fib = fibonacci_generator()
for _ in range(10):
print(next(fib))
In the above example, fibonacci_generator
the generator function uses yield
the keyword to define a generator that generates the Fibonacci sequence. next(fib)
The generator yields the value of the next Fibonacci sequence each time it is called .
8. Asynchronous functions
An async function is a form of function used in asynchronous programming that can be defined using async
the keyword . Asynchronous functions are usually used together with await
keywords to handle asynchronous operations, such as network requests, file reading and writing, etc. Asynchronous functions can improve the concurrency and responsiveness of a program, allowing other tasks to be performed while waiting for certain operations to complete. Here is an example of a simple asynchronous function:
import asyncio
async def greet(name):
print("Hello, " + name)
await asyncio.sleep(1)
print("Goodbye, " + name)
asyncio.run(greet("Alice"))
In the above example, greet
the async function uses await
the keyword to wait for the async operation asyncio.sleep(1)
to complete. While waiting, other tasks can be performed. Such an asynchronous function can improve the performance of the program in the case of needing to wait for I/O operations.
9. Partial functions
A partial function is a functional form that fixes some of the parameters of a function. It works by using functools.partial()
a function to create a new function that fixes some of the parameters of the original function. Partial functions can be used to simplify function calls and reduce repetitive code. Here is an example using partial functions:
import functools
def power(base, exponent):
return base ** exponent
square = functools.partial(power, exponent=2)
cube = functools.partial(power, exponent=3)
print(square(4)) # 输出:16,等同于 power(4, 2)
print(cube(4)) # 输出:64,等同于 power(4, 3)
In the example above, functools.partial()
the function creates two new partial sums square
, cube
which are power
specific versions of the function where exponent
the arguments are fixed to 2 and 3.