博客
关于我
python 中的函数定义
阅读量:662 次
发布时间:2019-03-15

本文共 1069 字,大约阅读时间需要 3 分钟。

函数定义:

def 函数名(参数):

函数体
单独打印函数名时会显示函数地址

调用函数:函数名+(参数)

def func(a):    print(a)print(func)func('value')# 输出结果:
value

查看数据类型和判断数据类型的函数:

type() 查看数据的数据类型
isinstanse() 判断数据是否是指定的数据类型,返回值为bool值

l1 = [1, 2, 3, 4]print(type(l1))print(isinstance(l1, list))# 输出结果:
True

关键字参数:可以在命名函数是定义参数的值,调用时如果传参则按调用时的值计算,不传则按定义时的值计算

def func(a='default'):    print(a)func()func(a='value')# 输出结果:default  # 不传参时输出的默认值value

return 返回值

1.return后面可以是一个参数,接收时 a= add(1,2)
2.return后面是多个参数,如果是多个参数则底层会将多个参数先放在一个元组中,
将元组作为整体返回, a= add(1,2) a------>(1,2,3)
3.接受的时候也可以是多个参数 return a,b ------> a,b=add(1,2) -------> a = a b = b

def add(a, b):    result = a + b    print(result)    return result, a, bresult = add(3, 5)print(result)# 输出结果:8  # 8为调用函数add的打印(8, 3, 5)  # 元组为result的打印

函数中的全局变量:将函数外层的变量声明为全局变量,所有函数都可以访问

全局变量如果是不可变,在函数中进行修改需要添加global关键字,如果全局变量是可变的,在函数中修改的时候就不需要加global关键字

s = 5l = [1, 2, 3]def func():    global s  #  s为整型,是不可变数据类型,需要添加global才可以修改    s += 1    l.append(s)  # l为列表,是可变数据类型,不需要添加关键字,可以直接修改    return s, lresult = func()print(result)# 输出结果:(6, [1, 2, 3, 6])

转载地址:http://dmxmz.baihongyu.com/

你可能感兴趣的文章
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>