Python function module

1) Python function

1. Function definition and call

The function definition format is as follows:

def 函数名称(参数列表):
    函数体

– [Example] Function to print information

#定义一个函数,能够完成打印信息的功能
def print_info():
    print('hello python!')
#调用函数
print_info()

Special attention should be paid to the following points in the Python function definition:

  • def is a keyword to define a function, which is an abbreviation of the English word define.
  • The naming rules of function names must conform to the basic rules of naming identifiers in Python. Function names are generally composed of letters, numbers and underscores.
  • The function name is followed by English state parentheses. There can be many parameters or no parameters. They are all variables of the function. These parameters are called the formal parameters of the function (referred to as formal parameters).
  • The function body is the program code of the function, and its position is indented four spaces or one tab relative to the def keyword. After defining a function, it is equivalent to having a piece of code with a specific function. To make these codes execute, you need to call the function. The method of calling a function is very simple, and the call can be completed by "function name ()".

2. Function parameters and return values

The role of function setting parameters: to make the function more general, and to output corresponding results according to any incoming value.
– [Example] Call the add function to find the sum of two numbers

#无参数函数定义
def add():
    c=10+20
    print("两数的和是:",c)
#函数调用
add()

#有参数函数定义
def add(a,b):
    c=a+b
    print("两数的和是:",c)
#函数调用
add(10,20)

Function arguments: positional arguments, keyword arguments, default arguments, variadic arguments

  1. Positional parameters: When calling a function, parameters are passed according to the parameter position defined by the function.
  2. Keyword parameters: specified in the form of "key-value", which can make the function clearer and easier to use, and at the same time remove the order requirement of the parameters.
  3. Variable parameters: When defining a function, sometimes it is not sure how many parameters will be passed when calling. At this time, the number of parameters passed in is variable, which can be 1, 2 to any, or 0 .
  4. Default parameters: used to define functions, provide default values ​​for parameters, and may or may not pass default parameter values ​​when calling a function. Note that all positional parameters must appear before default parameters, including function definitions and calls.
a.Default parameters

Definition: When defining a function, you can set default values ​​for the parameters of the function, which are called default parameters.
– [Example] The function sum of RMB to USD.

#函数定义
def RMB_to_dollar(money,rate=0.1442):
    dollar=money*rate
    print("兑换的美元为:",dollar)
#函数调用
RMB_to_dollar(1000)
b. Any number of positional variadic arguments

When defining a function, the exact number of parameters is uncertain. Using *args and **kwargs in python can define variable parameters, and you can define 0 to any number of parameters before the variable parameters.
The basic syntax format is as follows:

def 函数名([formal_args,] *args, **kwargs):
函数体

– [Example] For a function with variable length parameters, pass in different numbers of parameters respectively, and test the running results:

 def test(a,b,*args): 
       print(a) 
       print(b) 
       print(args) 
test(10,20)
c. The return value of the function

Definition: Refers to the result returned to the caller after the function in the program finishes running. In Python, the return value of a function is done using the return statement.
The format is:

return 表达式

– [Example] Define a function to calculate the sum of two numbers, and use the sum value as the return value of the function.

def add(a,b):
    c=a+b
    return c
d. Four types of functions

According to whether there are parameters and return values, functions can be roughly divided into four types:

  • no parameters, no return value
  • With parameters, no return value
  • no parameters, return value
  • It has parameters and a return value

2) Python variable scope

1. Local variables

Local variables, also called internal variables, refer to variables defined inside a function. The scope of a local variable is the function that defines the variable, and the lifetime of a local variable is calculated from the time the function is called to the time the function returns to the calling place. It is valid only when the program executes this function, and the local variables are destroyed after exiting the function. Local variables between different functions are different, even if they have the same name, they will not interfere with each other. The local variable has locality , which makes the function independent. The interface between the function and the outside world is only the function parameter and its return value, which makes the modularization of the program more prominent, which is conducive to the modular development of the program.

2. Global variables

Global variables are global and are a common way to exchange data between functions. The scope of global variables is the entire program. They exist at the beginning of a function and are destroyed when the program ends.
– [Example] Define the function sum() to calculate the cumulative sum.

result=100                     #全局变量
def sum(m):
    result=0                   #局部变量
    for i in range(m+1):
        result=result+i         
    print("函数内的result值为:",result)
    return result
sum(100)
print("函数外的result值为:",result)

Note: If a global variable is to be used inside a function, the variable can be declared as a global variable in the function, so that the variable used inside the function is a global variable. At this time, when changing the value of the global variable in the function, it will directly affect the value of the global variable outside the program.

result=100                     #全局变量
def sum(m):
    global result              #声明使用全局变量
    for i in range(m+1):
        result=result+i
    print("函数内的result值为:",result)
    return result
sum(100)
print("函数外的result值为:",result)

3) Function call

In Python, all function definitions are parallel, and functions are allowed to call each other, and nested calls are also allowed. The execution of the program always starts from the main function, returns to the main function after completing the calls to other functions, and finally ends the whole program by the main program function. Nested calls are when a function calls another function, and the called function further calls another function, forming a layer-by-layer nesting relationship.
In the nested call of the following functions, the function fn3 calls fn2 in the function body, then calls fn1 through fn2, prints out "this is function fn1", and completes the entire calling process. The specific functions are implemented as follows:

# 函数的嵌套调用:在一个函数内部调用另一个函数
def fn1():
    print("这是函数fn1")
def fn2():
    print("这是函数fn2")
    fn1()  # 函数的嵌套调用
def fn3():
    print("这是函数fn3")
    fn2()  # 函数的嵌套调用
fn3()

– [Example] Find the maximum value among four numbers by using function nested calls.

# 求两个数最大值
def max_two(n1, n2):
    if n1 > n2:
        return n1
    return n2
# 求三个数最大值
def max_three(n1, n2, n3):
    max = max_two(n1, n2)
    return max_two(max, n3)
# 求四个数最大值
def max_four(n1, n2, n3, n4):
    max = max_three(n1, n2, n3)
    return max_two(max, n4)
max= max_four(20, 50, 30, 50)
print(max)

4) python module

1. Basic use of modules

In python, a certain module can be introduced through the import keyword, for example, to import the math module, you can use import math to import it. After the introduction, if you need to call the square root function sqrt() in the math module when writing the program, you must refer to it like "module name.function name", that is, "math.sqrt()".
– [Example] Find the square root of 4.

import math
a=math.sqrt(4)
print(a)

The module imported into the python project file can be aliased when it is imported to facilitate the code writing in the subsequent program. For example, the alias of the imported numpy module is np, and the calling function randomly generates an integer between 0-100.
–[Example] Randomly generate an integer between 0-100.

import numpy as np
x=np.random.randint(0,100)
print("产生的随机数为:",x)

2. Use of custom modules

In python, each python file can be regarded as a module, and the name of the module is the name of the file. Assume that there is an existing file myModule.py, which defines two functions myMin and myMax, as shown below:
– [Example] Realize two functions myMin and myMax, and calculate the minimum and maximum values ​​respectively.

def myMin(a,b):
        c=a
        if a >b:
                c=b
        return c
def myMax(a,b):
        c=a
        if a<b:
                c=b
        return c

Save myModule.py to E:\Users\Administrator\PycharmProjects\. At this time, if you create a new main.py file under the same path, you can introduce the myModule module in main.py and use its myMin and myMax functions.
The specific main.py code is as follows:

import myModule
min=myModule.myMin(5,8)
max=myModule.myMax(5,8)
print("大数是:",max)
print("小数是:",main)

Guess you like

Origin blog.csdn.net/xiaoyu070321/article/details/132153970