Python Basics-08 Function Basics

what is a function

  • A bunch of prepared codes that can be called when needed
  • Disadvantages represented by repeated code: redundancy, poor maintainability
  • So, to pack multiple lines of code into one whole: the function
  • In Python, use the keyword def to declare a function
# def 函数名():
#   函数要执行的操作
  • After the function is defined, it will not be executed automatically
  • Need to use the function name (parameter) to call
  • A function name is also an identifier
  • Composed of numbers, letters, and underscores, cannot start with a number, and is strictly case-sensitive; keywords cannot be used
  • Comply with the naming convention and use an underscore to connect; as the name implies: the logic executed by the function should preferably be consistent with the name of the function

function parameters

  • When a function is declared, the parameters in parentheses are called formal parameters, or formal parameters for short.
  • The value of the formal parameter is indeterminate, it is only used as a placeholder
  • When calling a function, you can pass formal parameters
  • The parameters passed in when the function is called are the real data involved in the operation, which we call actual parameters
  • When the function is called, the actual parameters will be passed to the formal parameters in one-to-one correspondence.
  • You can also specify the variable name and pass the actual parameter to the formal parameter

function return value

  • The return value is the execution result of the function, but not all functions must have a return value
def add(a,b):
    c = a+b  # 变量C在外部是不可见的,只能在函数内部使用
    return c  # return 表示一个函数的执行结果

result = add(1,2)
print(result ** 4)
  • If a function does not return a value, it will return None

Documentation for the function

  • Use a pair of three quotation marks, in the function body, to indicate the description of the function
def add(a,b):
    """
    a: 第一个参数
    b: 第二个参数
    该函数返回两个数字相加的结果
    """
    return a+b
  • When writing a function, add: int after the formal parameter to specify the type of the actual parameter you want to pass in
def add(a:int,b:str):  # 希望a的类型是int,b的类型是str
    pass

function call function

  • In function 2, function 1 can be called directly. When function 2 is called, function 1 will be called according to the position of function 1 in the code of function 2. The demonstration is as follows:
def function_1():
    print('函数1开始了')
    print('函数1结束了')

def function_2():
    print('函数2开始了')
    print('开始调用函数1')
    function_1()
    print('函数1调用结束')
    print('函数2结束了')

function_2()

# 函数2开始了
# 开始调用函数1
# 函数1开始了
# 函数1结束了
# 函数1调用结束
# 函数2结束了

# 求m阶乘的和
def fac(n):
    x = 1
    for i in range(1,n+1):
        x *= i
    return x

def sum(m):
    x = 0
    for i in range(1,m+1):
        x += fac(i)
    
    return x

print(sum(5))

Global and local variables

  • Python can use functions to separate scopes
  • Variables defined outside the function are global variables and can be accessed throughout the py file
  • The variable defined inside the function is a local variable, which is a local function and can only be used inside the function
  • The built-in function globals() locals() can print the global variables and local variables in the function
a = 100  # a是全局变量
word = 'hello'

def test():
    b = 80  # b是局部变量
    a = 10  
    print(a)
    # 如果在函数内部声明了一个与外部全局变量相同名称的变量,会新建一个函数内部的局部变量
    # 而不是修改外部的全局变量
    # 如果需要修改全局变量,可以使用global关键字
    global word
    word = 'thank'
    print(word)
    print('locals = {},globals = {}'.format(locals(),globals()))  # ocals = {'b': 80, 'a': 10},globals = {'__name__': '__main_........ 全局变量非常多

test()  # 10
print(a)  # 100

print(word)  # thank

Function multiple return values

  • return indicates the end of a function
  • Under normal circumstances, a function will only execute at most one return statement
  • In special cases (finally statement), the next function may execute multiple return statements
def test(a,b):
    x = a // b
    y = a % b

    # return x 
    # return y
    # 以上代码只会执行一个return

    # return {'x':x,'y':y}  # 以字典的形式返回
    # return [x,y]  # 以列表的形式返回
    # return (x,y)  # 以元组的方式返回
    return x,y  # 返回的本质实际上就是返回一个元组

print(test(12,5))  # (2, 2)

Use of default parameters

  • The parameters of some functions, if you pass parameters, use the passed parameters, if you do not pass parameters, use the default value
# print函数中,end就是一个缺省参数
print('hello',end = '')
print('你好')
# hello你好
  • How to set the default value of a formal parameter: When defining a function, directly give a value to the formal parameter at the formal parameter that needs a default value
  • If no parameter is passed, the default value will be used. If the parameter is passed, the passed parameter will be used, as follows
def say_hello(name,age,city='hangzhou'):
    print('大家好,我叫{},我今年{}岁了,我来自{}'.format(name,age,city))

say_hello('lzh',18)  # 大家好,我叫lzh,我今年18岁了,我来自hangzhou
  • A single parameter can be passed directly, or it can be passed in the form of variable assignment
  • If there are positional parameters and keyword parameters, the keyword parameters must be placed after the positional parameters
def say_hello(name,age,city='hangzhou'):
    print('大家好,我叫{},我今年{}岁了,我来自{}'.format(name,age,city))

say_hello(name ='lzh',city ='sichuan',age =18)  # 大家好,我叫lzh,我今年18岁了,我来自sichuan

The use of variable parameters

  • Use *args to represent variable positional parameters --> save in the form of tuples
  • Use **kwargs to represent variable keyword parameters --> save in the form of a dictionary
def add (a,b,*args):  # args 表示可变参数,必须有两个参数
    pass
add(1,4,65,7,8,43)  # 多出来的可变参数会以元组的形式保存到args中

def add(*args):  # 仅有可变参数
    pass

def add(a,b,*args,mul=2):  # 如果有关键字参数,需要放在可变参数之后
    pass

def add(a,b,*args,mul=2,**kwargs):  # 可以用 ** kwargs 来接受多余的关键字阐述
    pass

Notes on functions

  • The three elements of a function
    • Function name
    • parameter
    • return value
  • In some programming languages, function duplication is allowed, but function duplication is not allowed in Python
  • If the function has the same name, the latter function will overwrite the previous one
  • In Python, a function name can also be understood as a variable name
  • Therefore, when defining a function, do not have the same name as the built-in function

function recursion

  • Simply put, recursion means that the function itself calls itself
  • The most important thing about recursion is to find the exit (stop condition)
# 使用函数递归求1-n的和
x = 0
def get_sum(n):
    global x
    x += n
    n -= 1
    if n >= 1:
        get_sum(n)
    return x

print(get_sum(100)) # 5050

# 递归方法2
def get_sum2(n):
    if n == 0:
        return n
    return n + get_sum2(n-1)

print(get_sum2(100))  # 5050

# 使用函数递归求n!
def get_num(n):
    if n == 0:
        return 1 
    return  n * get_num(n-1)

print(get_num(0))  # 1

# 斐波那契数列的第N个数字
def get_fi(n):
    if n == 2 or n == 1:
        return 1
    return get_fi(n-2) + get_fi(n-1)

print(get_fi(8))  # 21

anonymous function

def add(a,b):
    return a+b

x = add(1,2)  # 函数名(实参)作用是调用函数,获取到行数的执行结果并赋值给变量 x

fn = add  # 相当于给函数add起了一个别名叫fn

  • Using the keyword lambda can be used to define a function
  • Anonymous function, used to express a simple function
  • How to call an anonymous function:
    • The first: define a name for him (rarely used like this)
    • The second: pass this function as a parameter to another function to use
lambda a,b: a+b  
fn2 = lambda a,b: a+b  # 第一种调用方法

def calc(a,b,fn):
    c= fn(a,b)
    return c

x3 = calc(1,3,lambda x,y: x+y)  # 第二种调用方法:借用回调函数
print(x3)

Use of the sort method

  • Partial list of built-in functions and built-in classes, using built-in functions
# 列表的 sort 内置方法会直接对列表进行排序
# sorted 内置函数,不会改变原有的数据,而是生成一个新的结果
students = [
    {
    
    'name':'zhoujielun','age':18,'sorce':97,'height':180},
    {
    
    'name':'linjunjie','age':22,'sorce':65,'height':177},
    {
    
    'name':'caiyilin','age':20,'sorce':88,'height':185}
]

# 字典和字典之间不能使用比较运算
# students.sort()  # '<' not supported between instances of 'dict' and 'dict'

# 需要传递一个 key 参数,指定比较的规则
# key 的参数类型是一个函数
# def foo(ele):
#     return ele['age']  # 在foo方法中,指定按照年龄进行排序

# students.sort(key=foo)  
# 在sort方法中,会调用key中给定的函数,并且传入参数,参数是列表中的元素
# [{'name': 'zhoujielun', 'age': 18, 'sorce': 97, 'height': 180},
#  {'name': 'caiyilin', 'age': 20, 'sorce': 88, 'height': 185}, 
# {'name': 'linjunjie', 'age': 22, 'sorce': 65, 'height': 177}]

# 简化sort函数
students.sort(key= lambda ele:ele['height'])
# [{'name': 'linjunjie', 'age': 22, 'sorce': 65, 'height': 177}, 
# {'name': 'zhoujielun', 'age': 18, 'sorce': 97, 'height': 180}, 
# {'name': 'caiyilin', 'age': 20, 'sorce': 88, 'height': 185}]

print(students)

Use of filter map reduce built-in classes

  • filter can filter iterable objects and get a filter object
  • In Python2, it is a built-in function, in Python3, it is modified into a built-in class
# fliter 可以给定两个参数
# 第一个参数是一个函数
# 第二个参数是可迭代对象
# filter返回的结果是一个fiilter类型的对象
# filter对象本身也是一个可迭代的对象

x = filter(lambda a: a%2 == 0,range(1,10))
print(x)  # <filter object at 0x0000024ED08E9FA0>
print(list(x))  # [2, 4, 6, 8]
for i in x:
    print(i,end='')  # 2468

# map 内置方法,将可迭代对象中所有的元素按照map指定的方法处理
# 返回一个map类型的可迭代对象
ages = [10,11,25,16,8,14,46,547]

m = map(lambda a: a+2,ages)
for x in m:
    print(x,end=' ')  # 12 13 27 18 10 16 48 549

# reduce 以前是一个内置函数,现在在functools模块中
# 内置函数和内置类都在 builtin.py 文件中定义
from functools import reduce
def foo(x,y):
    return x + y 

scores = [100,154,1564,4684]

print(reduce(foo,scores))  # 6502

# 使用内置方法,求students中所有的age相加
from functools import reduce

students = [
    {
    
    'name':'zhoujielun','age':18,'sorce':97,'height':180},
    {
    
    'name':'linjunjie','age':22,'sorce':65,'height':177},
    {
    
    'name':'caiyilin','age':20,'sorce':88,'height':185}
]

# 使用map函数先处理获取age,再使用reduce进行相加
print(reduce(lambda x1,x2:x1+x2,map(lambda a: a['age'],students)))  # 60

# 或者直接给定reduce的初始值为0,那么第一轮运算时,给的第一个x的值就是0
print(reduce(lambda x1,x2:x1+x2['age'],students,0))  # 60

Guess you like

Origin blog.csdn.net/Lz__Heng/article/details/130192223
Recommended