python基础之函数

来源:互联网 发布:linux arp命令 编辑:程序博客网 时间:2024/05/01 07:36

一、函数定义,参数,以及返回值

def 函数名():

函数体

返回值:通过return函数

>>> def fun():>>> def add(a,b):print(a+b)>>> add(34,78)112>>> def add1(a,b):return a*b>>> add1(12,5)60>>> 


print('第一个函数')>>> fun()第一个函数>>> def fun(name):print("第二个函数"+name)>>> fun(age)Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> fun(age)NameError: name 'age' is not defined>>> fun('age')第二个函数age

二、函数文档

>>> def fun(name):'函数定义过程的name是形参!'#因为表示一个形式,标志占据一个位置print('传递参数'+name+'是实参,有具体参数值')>>> fun('xiao')传递参数xiao是实参,有具体参数值
>>> fun._doc_Traceback (most recent call last):  File "<pyshell#23>", line 1, in <module>    fun._doc_>>> help(fun)Help on function fun in module __main__:fun(name)    函数定义过程的name是形参!


关键参数

>>> fun(name='关键参数')传递参数关键参数是实参,有具体参数值>>> 

收集参数

参数前加*

>>> def test(*param):print("参数的长度是:",len(param))print("第一个参数是:",param[1])>>> test(1,2,3,4)参数的长度是: 4第一个参数是: 2>>> 

>>> def test(*param):print("参数的长度是:",len(param))print("第一个参数是:",param[1])>>> test(1,2,3,4)参数的长度是: 4第一个参数是: 2>>> def test1(*param,exp)SyntaxError: invalid syntax>>> def test1(*param,exp):print("参数的长度是:",len(param))print("第一个参数是:",param[1])print('exp是:',exp)>>> test1(1,2.3,4,exp="普通参数")参数的长度是: 3第一个参数是: 2.3exp是: 普通参数>>> 

函数与过程:

函数有返回值,python中只有函数、、


全局变量和局部变量:

def discount(price,rate):    final_price=price*rate    return final_priceold_price=float(input("请输入原价:"))rate=float(input("请输入折扣率:"))new_price=discount(old_price,rate)print("打折后的价格:",new_price)

内嵌函数和闭包

>>> count=5#全局变量>>> def myfun():count=10#局部变量print(10)>>> myfun()10>>> print()countSyntaxError: invalid syntax>>> print(count)5>>> 

全局变量用global申明:

>>> def myfun():global countcount=10print(count)>>> nyfin()Traceback (most recent call last):  File "<pyshell#63>", line 1, in <module>    nyfin()NameError: name 'nyfin' is not defined>>> myfun()10>>> print(count)10>>> count=1>>> print(count)1>>> myfun(count)Traceback (most recent call last):  File "<pyshell#69>", line 1, in <module>    myfun(count)TypeError: myfun() takes 0 positional arguments but 1 was given>>> myfun()10>>> 


原创粉丝点击