[Python Basic Tutorial] One article to clarify the details of Python functions


foreword

What is a function? In middle school or in the field of mathematics, you may get this answer: The definition of a function is given a set of numbers A, assuming that the elements in it are x, apply the corresponding rule f to the elements x in A, denoted by f(x) , get another number set B, assuming that the element in B is y, then the equivalent relationship between y and x can be represented by y=f(x), the function concept contains three elements: domain A, value domain B and the corresponding law f. The core of which is the corresponding law f, which is the essential feature of the functional relationship. But in our computer field function has another understanding, it is sacred. It refers to a piece of program or code that can be directly referenced by another piece of program or code. Also called subroutines, (in OOP) methods. A larger program should generally be divided into several program blocks, each of which is used to implement a specific function. All high-level languages ​​have the concept of subroutines, and subroutines are used to implement the functions of modules. Today, we will lead you to understand what is the function of the computer language.


insert image description here


1. Why do computers have functions?

  • Sometimes a piece of code may be used many times, each time only the size of the variable changes slightly. If it is not encapsulated into a function
    , it may need to be written repeatedly every time it is used. Writing a function can realize a piece of code that can be reused
  • For computer programming, we expect the modular design of the program, and the function is a typical example of modularizing the code. By loading a piece of code that can achieve a certain function into a function, and then calling the corresponding function when it is used.
  • The use of functions can make the code more rigorous and organized.
  • Divide a project into many small modules, and then multiple people can collaborate. Improve development efficiency
  • The recursion of functions can easily implement many algorithms such as: Tower of Hanoi

Second, the function classification of Python

1. Built-in functions

To put it bluntly, it is the functions that can be used directly without importing the package after you download Python IDEL,
such as print(), abs(), len(), etc.

code show as below:

print("Hello")
abs(-1)
len("Hello World")

2. Standard library functions

The standard library will be installed with the installation of Python, but when using the package inside, it needs to be imported first
. The rules used are as follows:

code show as below:

import math
print(math.pi)

3. Third-party library functions

The most typical feature of third-party libraries is that they need to be downloaded or installed separately, and
then imported and used after installation.

code show as below:

import pandas as pd
data = pd.read_csv(
    'https://labfile.oss.aliyuncs.com/courses/1283/adult.data.csv')
print(data.head())

4. User-defined functions

The function name of the function defined by yourself, the function name is set by yourself, and the function of the function is customized by yourself.
This is also what we want to emphasize today. Let's take a look at a formed function.

code show as below:

def print99():
	for teg in range(1,10):
	   temp=1
	   while temp<=teg:
	      print(str(temp)+'*'+str(teg)+'='+str(teg*temp),end='  ')
	      temp+=1
	   print()
if __name__=="__main__":
	print99()

Three, the components and characteristics of functions in Python

1. Declare a function

The composition of a function is roughly like this [function declaration]

'''
def是对函数进行声明,f为函数名
Python语句块是要求格式化的,所以函数体(这里pass做的占位符)在
函数声明下要进行缩进,并且参数列表括号后面要跟上:(冒号)
'''
def f(参数列表):
	pass

2. Analysis of function characteristics

Features of functions in Python:

  • The function is relatively simple to use, as in other languages, the function name is called with parentheses (but the function must be declared before calling the function)
  • A function can have a return value but it does not have to have a return value (the result is None after the function without return value is executed)
  • A function is an expression that can be used directly for calculations (addition, subtraction, multiplication and division)
  • Functions in Python can be directly assigned as variables.
  • Python function returns a value, but supports multiple return values ​​after operation (can return a tuple, tuple memory multiple values)

Function from declaration to execution:

  • def is the execution statement. Python interprets and executes the def statement to create a function object and bind it to the function name variable
  • Before calling a function, you must execute the def statement, that is, the declaration of the function, and create a function object.
  • When executing, use the function name (), that is, the corresponding function object to implement the function call.
  • When using external functions, import the package first, and initialize the function object when importing the package.

4. Detailed explanation of function parameters

1. Divide according to the definition of parameters

①Formal parameters

Formal parameters, as the name suggests, are only a formal parameter, mainly used for parameter type declaration of functions. It is not obvious in Python, but it can be clearly reflected in C or C++. The parameter list of a function declaration in C++ can only write the type of the function. Then when calling the function, pass in the parameters of the corresponding type. The scope of formal parameters is only within the scope of the function.

②Actual parameters

The actual parameter, as the name suggests, is the actual parameter, in other words, the parameter that is actually passed in when the function is called. At this time, the parameter variable type should correspond to the formal parameter of the function, and the value should be given artificially.

#此时的i就是形式参数、“Tom”就是实际参数
def pType(i):
	print(type(i))
	
pType("Tom")

2. Divide according to the use of parameters

According to the definition of parameters, it can be divided into formal parameters and actual parameters. According to the usage of parameters, it can be divided into positional parameters, variable parameters, optional parameters, and named parameters.

①Location parameter

位置参数的意思就是根据形式参数的位置,传入相应的实际参数。函数的参数列表是有限个
并且参数没有默认值,调用函数的时候必须在对应位置传入对应参数。
def pType(i):
	print(type(i))

②Variable parameters

前面提到了位置参数,是有限个并且必须在指定位置传入指定参数。
可变参数与其相反,它可以传入任意个数个参数,并且类型无需保持一致。
可变参数的传参方方式有两种一种是变量前加单*,一种是变量前加双*。
加单星的称为元组可变参数,加双星的是字典可变参数。(可变参数一般放在参数列表的末尾)
要切记如果元组可变参数与字典可变参数同时出现在函数参数列表中要将元组可变参数放在前面

[1] tuple varargs

元组可变参数指的是传进来的参数会以元组的形式进行储存。
def pr1(a,b,*c):
    print(a)
    print(b)
    print(c)

[2] Dictionary variable parameters

字典可变参数是传进来的参数会以字典的形式进行储存,最典型的特征就是传参时必须以命名参数形式传参
命名参数接下来会讲,使用这种方式的原因得益于字典可变参数是字典形式,要有键值对。
def pr2(a,b,** c):
    print(a)
    print(b)
    print(c)

[3] Dictionary tuple variadic parameters

字典可选参数放在参数列表最后,因为元组可选参数根据位置进行选参,如果将其放在字典可选参数后面会
导致命名参数后面的参数无法传入,程序抛出异常。而将命名参数放在最后正好弥补这种缺陷。
def pr3(a,b,*c,**d):
    print(a)
    print(b)
    print(c)
pr3(1,2,3,age=4,p=2,q=3,w=4,e=3,r=24)

③Optional parameters

可选参数就是调用函数的时候可以传入该参数,也可以不传入该参数,如果不传人参数的话就使用
该参数在定义函数的时候的默认值。【如果参数列表有可变参数,传参的时候会先给可选参数再给可变参数】
def pr1(a,b=10):
    print(a)
    print(b)

④Named parameters

命名参数使用的时候要将参数名体现出来,也就是说,传参的时候可以跟参数位置无关,但是需要使用参数名传参
一般的情况下命名参数有可无,在有字典可变参数或者经过我们处理的时候,相关的参数必须显式传递。

Rough Form of Named Parameters

def pr1(a,b):
    print(a)
    print(b)
#这两种调用方式一样。
pr1(10,11)
pr1(b=11,a=10)

Mandatory named parameters

def pr1(*,a,b):
    print(a)
    print(b)
#这两种调用方式一样。
# pr1(10,11)		这种方式报错
pr1(b=11,a=10)

Five, recursive function

1. Definition

In computer languages, a function is called recursive if it calls itself.

# 汉诺塔
def h(n,a,b,c):
	if n==1:
		print(a,"--->",c)
	else:
		h(n-1,a,c,b)
		h(1,a,b,c)
		h(n-1,b,a,c)
h(4,"A","B","C")

2. Conditions that recursive functions need to meet

  • Recursion must have termination condition
  • It must be ensured that the relevant variables converge to the termination condition as the number of recursion increases
  • It must be clear that the number of recursion cannot be too many, and the number of recursion exceeding the limit will affect the computer memory.

6. Functional programming

Functional programming is a way of programming. The most important thing about functional programming languages ​​is that functions can accept functions as input (parameter) and output (return value). Compared with imperative programming, functional programming emphasizes that the computation of functions is more important than the execution of instructions. In contrast to procedural programming, the computation of functions in functional programming can be called at any time.

1. Function object

As a function in Python, it exists in the form of an object. Objects can be used for parameter passing, as return values,
as variable assignments, and so on.

2. Higher order functions

A function is called a higher-order function if the parameter or return value of a function contains another function.

3. Lambda expressions and anonymous functions

Many built-in functions in Python are higher-order functions, such as map and filter. When using them, it is often
necessary to pass a function in as a standard for handling variables. Such functions that are passed as parameters are called callback functions.
Generally not very large, only need to meet some small functions. So we like to pass anonymous functions in.
The function of lambda expression is to create a small anonymous function. The rules are as follows:
lambda parameter list: function body
The result of the following program is:
insert image description here

The * before map and filter means unpacking. List information is displayed.

print(*map(lambda x,y:x+y,range(5),range(5)))
print(*filter(lambda x:x%2==0,range(10)))

4. Simple use of function decorators

A function decorator is a shell that wraps around a function and is used to initialize the environment in which the inner function executes.
A decorator returns a modified function object, and a decorator is a design pattern. A function can have multiple decorators.
The specific syntax of the decorator is as follows:

import time
#装饰器函数
def timeit(func):
    def wrapper(*s):
        start=time.perf_counter()
        func(*s)
        end=time.perf_counter()
        print('运行时间:',end-start)
    return wrapper
#函数使用装饰器
@timeit
def mysum(n):
    sum=0
    for i in range(n):sum+=i
    print(sum)
#调用函数
mysum(10)

Summarize

Python is a language that supports both object-oriented and process-oriented, and everything in Python is an object, and functional programming makes it very flexible to program. Mastering functions proficiently can make our code more standardized. At this point, the function chapter is over, and you can learn more about function decorators. In this article, we will focus on mastering the use of parameters and lambda expressions.


insert image description here

Guess you like

Origin blog.csdn.net/apple_51931783/article/details/123119755
Recommended