python函数二

头歌Python实训答案——函数二 第1关:函数的参数 - 搭建函数房子的砖 编程要求 本关的编程任务是补全src/Step1/plus.py文件的代码,实现相应的功能。具体要求如下: 定义函数plus,功能是对参数(一个列表)中的数值元素进行累加,列表中的元素个数不确定; 函数返回累加结果。 #coding=utf-8 #创建一个空列表numbers numbers=[] #str用来存储输入的数字字符串,lst1是将输入的字符串用空格分割,存储为列表 str=input() lst1=str.spl... 阅读详情

返回值(return)

  • 返回值就是函数执行以后返回的结果
  • 用return来指定函数的返回值
  • 我们可以直接使用函数的返回值也可以通过变量来接受函数的返回值
  • return 后面可以跟任意对象,甚至是一个函数
def fn():
    # return 'python' # return可以返回任意对象
    # return (1, 2, 3)
    # return {'a':1, 'b':2}
    return 100
r = fn() # 用变量接受
print(r)    
print(fn()) # 直接打印,不推荐使用此法
# 100
# 100

下面代码中

  • fn2是函数对象,打印fn2实际上是打印函数对象,函数存储在内存中的地址(十六进制)
  • fn2()是调用函数,打印fn(),实际是在调用函数,打印得是函数的返回值
    两种方式都可以实现打印hello的效果,选用fn()时,r接收的是调用函数fn2(),打印r的结果就是hello
def fn():
    def fn2():
        print('hello')
    return fn2
r = fn() # 用r接收函数fn2对象
print(r) 
r()  # 调用函数
# <function fn.<locals>.fn2 at 0x0000015B8A6E55E8>
# hello     

若只写一个return,而没有返回值,会返回None

def fn():
    return
r = fn()
print(r)
# None    

在函数中return后面的代码不会被执行,一旦return执行就会自动结束函数

def fn():
    print('我执行了')
    return
    print('我睡着了')
r = fn()    
print(r)
# 我执行了
# None

文档字符串

help()函数可以查询其他函数的用法
help(print)
# print(...)
    # print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    # Prints the values to a stream, or to sys.stdout by default.
    # Optional keyword arguments:
    # file:  a file-like object (stream); defaults to the current sys.stdout.
    # sep:   string inserted between values, default a space.
    # end:   string appended after the last value, default a newline.
    # flush: whether to forcibly flush the stream.

为了提高代码的可读性,我们通常会对代码注释,解释说明该断代码
我写这篇博客时用的是vscode,可能是我没有安装这块儿插件吧,没有这个功能。pycharm中,在函数内输入三个引号‘’‘然后回车,会自动生成参数的说明,后面的备注需要自己写,这里为了举例子,随便写的。
下面fn(a:int, b:str, c:boll)参数后面的东西,不会有任何作用,知识起到注释的作用,但不建议这么写,这样容易出现错误。建议使用函数内部的注释方式。
->int的意思是返回的是一个整形

def fn(a:int,b:str,c:bool)-> int:

    '''
    :param a: 类型 int 默认值...
    :param b: 类型 str 默认值...
    :param c: 类型 bool 默认值...
    :return: int
    '''

    return 1

help(fn)
r = fn(5, 2, 3)
print(r)
# Help on function fn in module __main__:                                                           

# fn(a: int, b: str, c: bool) -> int
#     :param a: 类型 int 默认值...
#     :param b: 类型 str 默认值...
#     :param c: 类型 bool 默认值...
#     :return: int

# 1

## 函数的作用域

作用域指的就是变量生效的区域
全局作用域

  • 全局作用域在程序执行时创建,在程序执行结束时销毁
  • 所有函数意外的部分都是全局作用域
  • 在全局作用中定义的变量,都属于全局变量,全局变量可以在程序的任意位置访问

函数作用域

  • 函数作用域在函数调用时创建,在调用结束后销毁
  • 函数每调用一次会产生一个新的作用域
  • 在函数作用于中定义的变量都是局部变量,它只能在函数内部被访问到
a = 'i am global scope'
def fn():
    b = 'i am funcation scope'
    print('局部', b)
fn()    
print('全局', a)
# 局部 i am funcation scope
# 全局 i am global scope   

全局变量可以传入内部

a = 10
def fn():
    print(a)
fn()
# 10

但是函数变量不能在外部调用,函数外部是访问不到的
同时函数内部修改变量,不会影响到外部,且返回的结果已内部为准

a = 10
def fn():
    a = 20
    b = 10
    def fn2():
        a = 30
        print(a)
    fn2()
fn()
# print(b) 
# 30
# print(b)---NameError: name 'b' is not defined

若想通过函数内部改变全局变量需要用到global

a = 10
def fn():
    global a
    a = 20
    print('我是局部变量a', a)
fn()
print('我是全局变量a', a)
# 我是局部变量a 20
# 我是全局变量a 20

命名空间

命名空间实际上就是一个字典,是一个专门用来存储变量的字典
locals()

  • 用来获取当前作用域的命名空间
  • 如果在全局作用域中调用locals()则获取的是全局命名空间
  • 如果在函数作用域中调用locals()则获取的是函数命名空间
  • 调用locals(),返回的是一个字典
a = 10
def fn():
    a = 20
    b = 10
    def fn2():
        a = 30
        print(a)
    fn2()
fn()
s = locals()
s['b'] = 110 # 命名空间是一个字典,我们可以向正常字典一样,向里面添加键值对,但不推荐这么做,当你这么做的时候,别人可能就要打110了
print(s)
# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002DE2D25CD88>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'f:/my_dream/text.py', '__cached__': None, 
# 'a': 10, 'fn': <function fn at 0x000002DE2F3D5048>, 's': {...}, 'b': 110}

在内部函数中调用

a = 10
def fn():
    b = 20
    s = locals()
    print(s)
fn()   
# {'b': 20} 

递归

  • 递归简单的理解就是自己调用自己
  • 递归式函数,在函数中调用自己

递归的条件

  1. 基线条件
  • 问题可以被分解为最小的问题(即不再分解),但满足基线条件时,不再递归
  1. 递归条件
  • 将问题可以分解的条件

递归的练习

通过练习去学习递归,感受递归,下面的练习你可能会觉得问题复杂化了,当然解决问题的方法有很多,我想表达的是递归的思想

  1. 实现任意数的阶乘
  • 阶乘用’!‘表示,如5! = 12345
    我们想要实现一个小算法,首先先看看10!
    10!= 12345678910 = 109!
    9!= 123456789 = 98!
    …
    2!= 1
    2 = 2 * 1!
    1!= 1 = 1
def fn(n):
    # 基线条件,当n == 1时无法再分解
    if n == 1:
        return 1
    # 递归条件    
    return n * fn(n-1)
r = fn(6)
print(r)
# 720
  1. 创建一个函数来为任意数做幂运算 如 ni 54
    首先举个例子,看看65
    6
    5 = 66666 = 6 * 6 ** 4
    64 = 666*6 = 6 * 6 ** 3
    6
    3 = 666 = 6 * 6 ** 2
    6**2 = 6*6 = 6 * 6 ** 1
    6 = 6 = 6
def fn(n, i):
    if i == 1:
        return n
    elif n == 1:
        return 1
    return n * fn(n, i-1)
power = fn(6, 5)
print(power)
print(6**5)
# 7776
# 7776
  1. 创建一个函数,用来检测任意字符串是否是回文字符串,如果是返回True,如果不是返回False
    什么是回文字符串?
    字符串从后往前读和从后往前读是一样的 例如 abcba abc
    例如shellxllehs
    我们先看最左和最右的是不是一致
    shellxllehs
    hellxlleh
    ellxlle
    …
    x
    下面提供两段代码,第一段中,如果不判断elif len(s) != 1,会报错
    因为判断方式的不合理,造成了代码冗长,但是这是我做这个题目的第一想法,该方法仅做反面教材
def fn(s):
    if len(s) == 1:
        return True
    elif len(s) != 1:
        pass
    elif s[0] != s[-1]:
        return False
    return fn(s[1:-1])
r = fn('shellxllehs')
print(r)
# True

比较合理的方法,如下

def fn(s):
    if len(s) < 2:
        return True
    elif s[0] != s[-1]:
        return False
    return fn(s[1:-1])
r = fn('shellxllehs')
print(r)
# True
[Python从零到壹] 二.语法基础之条件语句、循环语句和函数 欢迎大家来到“Python从零到壹”,在这里我将分享约200篇Python系列文章,带大家一起去学习和玩耍,看看Python这个有趣的世界。所有文章都将结合案例、代码和作者的经验讲解,真心想把自己近十年的编程经验分享给大家,希望对您有所帮助,文章中不足之处也请海涵。Python系列整体框架包括基础语法10篇、网络爬虫30篇、可视化分析10篇、机器学习20篇、大数据分析20篇、图像识别30篇、人工智能40篇、Python安全20篇、其他技巧10篇。 阅读详情

相关推荐

《UVM实战》学习笔记——第三章UVM基础

uvm基础,常见的派生类,config db机制,打印信息等

qq_42135020的博客 5178

python之函数二

内容导读 函数参数之动态参数 函数的注释 函数的名称空间 函数的嵌套 global和nonlocal 函数参数之动态参数 简述 简述:之前我们说过传参,如果我们在传参的时候不清楚有哪些的时候,或者说给一个函数传了很多参数,我们就需要在函数定义的时候定义很多的参数,这样是非常麻烦的,因此,我们想要一个东西代替这一坨的参数,那么,这个东西就是动态参数。说白了就是我不管你这个函数会不会用到我们的参...

qq_40890660的博客 192

保姆级教程:在RK3588 Android12设备树(DTS)中配置MIPI 8 Lane双通道与DSC显示

本文详细介绍了在RK3588 Android12平台上配置MIPI 8 Lane双通道与DSC显示的实战指南。通过设备树(DTS)参数详解、DSC参数计算与PPS配置、双通道同步机制实现等内容,帮助开发者高效完成高分辨率屏幕驱动配置,解决嵌入式显示系统开发中的常见挑战。

weixin_30905133的博客 401

Python 的函数(二)

Python 的函数(二)1. 函数参数的类型1.1 必备参数 1. 函数参数的类型 在定义函数和调用函数时,函数的参数类型很重要;参数参数的类型有 必备参数、关键字参数、默认参数、不定长参数等等。 1.1 必备参数 必备参数要以正确的顺序传入函数;函数调用时实参的数量要和函数定义时形参一样。 例子1: ...

程序员小白的博客 852

《YOLOv8实例分割实战:训练自己的数据集 》(视频课程)

本课程将手把手地教大家使用labelme标注和使用YOLOv8训练自己的数据集,完成一个多目标实例分割实战项目。

bai666ai的博客 790

从公式到实践:用SPSS解锁香农多样性指数的生态洞察

本文详细介绍了如何利用SPSS软件计算和应用香农多样性指数进行生态研究。从基础公式解析到SPSS实战操作,再到生态决策支持,全面展示了该指数在物种丰富度和均匀度量化中的价值。文章特别强调了SPSS操作中的关键技巧和常见误区,为生态研究者提供了一套完整的分析解决方案。

weixin_30832143的博客 467

Python函数(二)※

python函数的调用

m0_70469414的博客 1592

微信小程序中使用画布canvas实现动态心电图绘制

近期,接了个项目,三端(小程序、PC、公众号)同步开发,PC端没的问题,以前一直做的就是PC端,但是小程序和公众号之前没有做过,只能通过这个项目,边做边学了。人家都说小程序用原生的特别难,大部分都用uniapp开发,说是这个方便快捷,还能写app呢,因为我们的项目,需要用到蓝牙采集数据、画布画仪表盘以及心电图等,所以我们不太敢用uniapp开发,硬着头皮开始用原生开发。开发的过程中,也遇到过很多问题,但是好在经过我们团队的不懈努力,问题基本都解决了。下面我就来分享一下,在小程序中,如何通过canvas。

穆雄雄的博客 3652

Python 函数(二)

Python 3 函数(匿名函数、偏函数 and 变量作用域:全局变量、局部变量)一、匿名函数:没有名字,也不再使用 def 语句这样标准的形式定义的一个函数。  1、python 3 使用 lambda 来创建匿名函数,;  2、lambda 只是一个表达式,函数体比 def 简单;  3、lambda的主体是一个表达式,而不是一个代码块,仅能封装有限的逻辑进去;  4、lambda 函数拥有自...

小麦粒的Python 1094

Windows配置L2TP/IPsec连接

Windows 系统的 L2TP/IPsec 功能,通过配置即可构建加密 VPN 通道。

m0_61806534的博客 1671

PyRoki:机器人运动学优化库入门教程

PyRoki:模块化机器人运动学优化工具包 本文介绍了PyRoki,一个模块化、可扩展且跨平台的机器人运动学优化工具包。PyRoki通过统一变量和成本函数接口,简化了逆运动学、轨迹优化和运动重定向等任务的实现,支持CPU、GPU和TPU加速。实验表明,PyRoki在批量逆运动学任务中比现有GPU加速库cuRobo快1.4-1.7倍,且收敛误差更低。其模块化设计支持快速集成新成本函数,并通过交互式可视化工具优化参数配置。PyRoki开源发布,为机器人运动优化提供了灵活高效的解决方案。

机器人控制与仿真应用 1294

python 函数二

向函数传递列表 将列表传递给函数后,函数就能直接访问其内容,这种列表包含的可能是名字,数字或更复杂的对象(如字典) def greeting_students(names): for name in names: print("Welcome to our university " + name.title() + "!") student_names = ["mengx...

AlwaysSpring的博客 297

DDS协议--[第一章][概述]

Data Distribute Service,数据分发服务:数据分发服务(DDS™)是一个由对象管理组(OMG)发布的以数据为中心的中间件协议和API标准。DDS集成系统中的各个组件,提供低延迟数据连接、高可靠性以及高可扩展体系结构,以适应商业级物联网(IoT)应用程序的需求。

qq_41816308的博客 1154

python--函数详解二

先看一段代码:运行结果:调用inner函数呢?运行结果:也就是说,内部函数inner不能再外部直接使用,会显示未定义的标识符,因为它在函数外部不可见。其实。

z541838的博客 736

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

Python—函数二

函数与过程 一般我们认为函数(function )是有返回值的,但过程(procedure)是简单的、特殊的、没有返回值的。 在Python一般来说是只有函数没有过程的: &gt;&gt;&gt; def hello(): print('hello ixaoyi') &gt;&gt;&gt; temp = hello() hello ixaoyi &gt;&gt;&gt; print...

键盘上的手艺人 160

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

【Python入门】Python的函数二

Python的函数二

weixin_42473228的博客 751

Python函数(二)

本文讲解Python编程的函数,围绕传递列表,传递任意数量的实参,将函数存储在模块中和函数编写指南展开。

Morse_Chen的博客 1560

python函数【二】:自定义函数

自定义函数 定义函数的语法格式为 def function_name(arg1, arg2, *, **): function_body return [expression] 不带表达式的return相当于返回 None。执行return语句后,自定义函数代码块中return语句后面的语句将不会被执行。 可利用*、**收集任意个 位置形参与 关键值形参 的值 指定默认参数值,在函数定义中,以“形参名=值”的形式指定某个形参的默认值;函数调用中,可以混合使用位置参数和关键值参数,但混用时,必须先指定

weixin_44815943的博客 1730

python函数总结二

python函数作用域一、 作用域1、作用域定义2、全局变量global3、nonlocal关键字4、默认值作用域二、闭包1、相关定义。2、函数调用函数3、闭包4、闭包的作用三、全局函数的销毁1、重新定义同名函数2、del 语句删除函数对象3、程序结束时四、局部函数销毁1、重新在上级作用域定义同名函数2、上级作用域销毁3、del语句删除函数对象 一、 作用域 1、作用域定义 ①、全局作用域:在整个程序运行环境中都可见 ②、局部作用域:在函数、类等内部可见;局部变量使用范围不能超过其所在的局部作用域 def

ClementCXL的博客 4781

python的函数二

1.函数的返回值 返回值:就是函数执⾏以后返回的结果。 可以通过return来指定函数的返回值。 return后面跟什么值,函数就会返回什么值。 return后⾯可以跟任意对象,返回值甚⾄可以是⼀个函数。 def fn(): def fn2(): print('haha') return fn2 r = fn() print(r) # <function fn.<locals>.fn2 at 0x0000025B62D60B70> r() #

newbiewww的博客 166

python中ls函数_python—函数实例二

一、递归几种常用内置函数方法:1)os.listdir():列出第一层目录文件In[14]:os.listdir("/root/python")Out[14]:['20.py','1.py','19.py','21.py']2)os.path.isdir():判断是不是目录In[13]:os.path.isdir("/root/python")Out[13]:True3)os.path....

weixin_39795971的博客 2178

li函数在python_二、python 函数

1.定义函数defmax(x,y):if x>y:returnxelse:return y如果定义空函数(函数还没想好怎么编写,只是为了让整个代码能够运行起来)defmax(x,y):pass2.函数的参数2.1可变参数顾名思义参数是可变的,既可以是1个参数,也可以是多个参数例:请计算a^2+ b^2 + c^2 + ……,其中a,b,c.....个数不确定,所以我们将参数用一个list或t...

weixin_36234970的博客 581

python函数(二)

Python高阶函数(如map、filter、reduce)支持以函数为参数或返回值,实现高效数据处理;变量作用域遵循LEGB规则(Local→Enclosing→Global→Built-in),需谨慎处理变量访问与修改;递归函数通过基线条件和递归条件解决问题,适用于阶乘等场景,但需权衡性能与栈溢出风险。文中还涉及函数内存分配机制,建议根据场景选择递归或循环。这些内容构成Python函数式编程与结构化设计的核心基础。

2301_77131592的博客 2006
上一篇: python集合&函数一
下一篇: python函数三
shell-x
博客等级 码龄7年 16粉丝 59原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值