Python function related notes

function:

Encapsulate the repetitive code into a function, enhance the modularity of the code and increase the reuse rate of the code.

format:
def 函数名([参数]):
    函数体(重复的代码)

Note: you must use the keyword def 2: function body pay attention to indentation 3: function body () binding

Definition function: random number generation
import random


def generate_random():

    for in in range(10):
    
        ran = random.randint()
            
        print(ran)
print(generate_random)


Execute: function generate_random at 0x000001390F096280 #If the function address is enclosed in parentheses, the whole function is executed directly

Call: the function finds the function and executes the content of the function body
generate_random()
16
18
5
15
12
6
10
20
3
10

Function: with parameters

    定义:
        def 函数名(参数):
            函数体
        调用
            pass        
Passing parameters for random numbers
import random


def generate_random(number): #形参 
    for i in range(number):
        ran = random.randint(1,20)
        print(ran)

generate_random(5) #实参 赋值
Keyword: isinstance
判断是什么类型
print (isistance(2,int) #判断2是不是整型 返回值False , True
True 
Mutable and immutable:
可变:地址不变里面内容改变 list dict set
不可变:只要内容改变,必须改变地址 int str float tuple frozenset
Variable function and immutable function pass parameters:
   def add(name,*args):
    sum = 0
    if len(args) > 0:
        for i in args:
            sum += i
        print('%s累加和是:sum:%s' % (name,sum))
    else:
        print("没有元素可计算,sum:" , sum)

add('狒狒',5,8,6,9)


运行结果:
    狒狒累加和是:sum:28

Variable parameters must be placed behind

Variable parameters + keyword parameters
Keyword parameters: key=value
    def add(a,b=10):
        result = a+ b
        print(result)
    
    add(5)
    
Definition dictionary
students = {
    
    '001':('蔡徐坤',21),'002':('王源',19),'003':('王俊凯',20),'004':('易烊千玺',19)}

def print_boy(persons):
    if isinstance(persons,dict):
        values = persons.values()
        print(values)
        for name,age in values:
            print('{}的年龄是:{}'.format(name,age))

print_boy(students)
*****************************
F:\code\venv\Scripts\python.exe F:/code/Study/day_20201228.py
dict_values([('蔡徐坤', 21), ('王源', 19), ('王俊凯', 20), ('易烊千玺', 19)])
蔡徐坤的年龄是:21
王源的年龄是:19
王俊凯的年龄是:20
易烊千玺的年龄是:19
Paired value call
def func(**kwargs): # key word argument
    print (a,b,c)
#调用
func(a=1 , b=2 ,c =3) #关键字参数

{'a': 1, 'b': 2, 'c': 3} #字典形式保存
def aa(a,b,*c,**d):
    print(a,b,c,d)

aa(1,2)
**********************
1 2 () {}

With *parameters with or without *tuples** dictionary

Variable parameter exercises
def func(a,*args):
print(a,args)

func(2,3,4,5) 
print('******************************')
func(2,[1,2,3,4])      
print('******************************')
func(2,3,[1,2,3,4,5]) 
print('******************************')
func(5,6,(4,5,6),9)

2 (3, 4, 5)
******************************
2 ([1, 2, 3, 4],)
******************************
2 (3, [1, 2, 3, 4, 5])
******************************
5 (6, (4, 5, 6), 9)


Variable scope:
a = 5  # 这是一个全局变量

def hello():
    a = 1  # a在这里是局部变量.
    print("函数内是局部变量 : ", a)
    return a

hello()
print("函数外是全局变量 : ", a)

Operation result The
function is a local variable: 1
Outside the function is a global variable: 5

global
如果想要在函数内部用模块定义的变量的话,就需要用到global关键字
a = 5

def hello():
    global a
    # 声明告诉执行引擎用的是全局变量a
    a = 1
    print('In test func: a = %d' % a)

hello()
print('Global a = %d' % a)

Running result:
In test func: a = 1
Global a = 1
You can see that the global variable a is successfully modified in the function

Local variables and global variables

Local variables:
函数内部声明的变量,局部变量
def func():
    s= 'abc' #局部变量

Global variables:
声明在函数外层是全局的,所有函数都可以访问
name = '月月' #全局变量
def func():
    pass
Loop nesting
name = '月月'
def func():
    s = 'abc'
    s += 'x'
    print(s,name)

def func1():
    global name
    print(name)
    name += "会弹吉他"
    print('func1修改后的name是:',name)

func()

func1()

func()

#输出结果:
abcx 月月

月月
func1修改后的name是: 月月会弹吉他

abcx 月月会弹吉他


If the global variable is modified in an immutable function, you need to add the global keyword. If the global variable is poor, you don’t need to add the keyword when you modify it in the function.

Internal function:

Features : can access external variables,
internal functions can modify variable variables of external functions,
nonlocal keywords can modify immutable variables

def func():
    n=5 #局部变量
    list = [5,3,6,15,12] 
    def inner_func():
        nonlocal n
        for index, i in enumerate(list):
            list[index] = i+n
            list.sort()
        n +=100
    inner_func()
    print(list,n)
func()
Default parameter
 end = ''  #缺省参数
 sep= "  "

recursive function

What is a recursive function

Through the previous study, we know that a function can call other functions.
If a function does not call other functions internally, but itself, this function is a recursive function.

The role of recursive functions

For example, let’s calculate the factorial n! = 1 * 2 * 3 *… * n

Solution 1: use loop to complete

def cal(num):
    result,i = 1,1
    while i <= num:
        result *= i
        i+= 1
    return result

print(cal(3))

See the law of factorial
1! = 1
2! = 2 × 1 = 2 × 1!
3! = 3 × 2 × 1 = 3 × 2!
4! = 4 × 3 × 2 × 1 = 4 × 3!
...
n! = n × (n-1)!

Solution 2: Use recursion to achieve
def factorial(num):
    result = 1
    if num == 1:
        return 1
    result = num * factorial(num -1)
    return result
print(cal(3))

principle

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-lABD7H68-1611304292725)(A0E4505279B6419FB2030A6E32066326)]

Anonymous function

Use lambda keywords to create small anonymous functions. This function gets its name from the omission of the standard procedure for declaring functions with def.

The syntax of the lambda function contains only one statement, as follows:

lambda 参数列表: 运算表达式

The following example:

sum = lambda arg1, arg2: arg1 + arg2
# 调用sum函数
print("Value of total : %d" % sum( 10, 20 ))
print("Value of total : %d" % sum( 20, 20 ))

The output of the above example:

Value of total :  30
Value of total :  40

Lambda functions can receive any number of parameters but can only return the value of an expression

Anonymous functions can execute arbitrary expressions (even print functions), but it is generally believed that the expression should have a calculation result for return.

Python can use lambda when writing some execution scripts, so that it can accept the process of defining functions, such as writing a simple script to manage the server.

Application occasion
Function passed as a parameter
>>> def fun(a, b, opt):
...     print("a = " % a)
...     print("b = " % b)
...     print("result =" % opt(a, b))
...
>>> add = lambda x,y:x+y
>>> fun(1, 2, add)  # 把 add 作为实参传递
a = 1
b = 2
result = 3

Guess you like

Origin blog.csdn.net/weixin_45767577/article/details/112988715