# 【Python基础】13-函数基础

1.1 定义

def函数名([形参]): 函数过程函数名([实参])#调用函数

defsayhi():#函数名

print('hello')sayhi()#如果不加括号只是表示该函数内存地址

1.1.1 函数特性

1.2 文档化函数

#开头

defsquare(x):

'calculates the square of number x'returnx*x

defsquare(x):

'calculates the square of number x'returnx*xprint(square.__doc__)

#输出

calculates the square of number x

1.3 并非真正函数的函数

python的有些函数并不返回任何东西，但是python的函数就是函数：没有return语句或者虽然有return语句后面没有跟任何值的函数不返回值

2.1 形参变量

2.2 实参

a,b=5,8defcalc(x,y):#x,y为形参res=x**y

returnresc=calc(a,b)#a,b为实参

print(c)

2.3 关键参数和默认参数

defhello_1(greeting,name):

print('%s，%s'%(greeting,name))

defhello_2(name,greeting):

print('%s，%s'%(name,greeting))

hello_1('hello','world')hello，world#输出

hello_2('hello','world')hello，world#输出

hello_1(name='hello',greeting='world')hello，world#输出

defstu_register(name,age,country,course):

print("----注册学生信息----")

print("姓名：",name)

print("age:",age)

print("国籍：",country)

print("课程:",course)stu_register("王二",22,"CN","python_devops")stu_register("张三",21,"CN","linux")

stu_register("王二",course="python_devops"，age=22,country='JP')

stu_register(course="python_devops"，"王二",age=22,country='JP')

stu_register("王二"，22，age=22,course="python_devops")

defstu_register(name,age,course,country="CN"):

print("----注册学生信息----")

print("姓名：",name)

print("age:",age)

print("国籍：",country)

print("课程:",course)stu_register("王二",22,"python_devops")stu_register("张三",21,"linux",'Korean')

2.4 收集参数

#报警，1个运维人员

print(msg)

print(user)#报警，10个运维人员

#输出

#输出

#输出

TypeError: send_alert() got an unexpected keyword argument'user'

#输出

deffunc(name,*args,**kwargs):

print(name,args,kwargs)func("Alex",22,"tesla","500W")

#输出

lex (22,'tesla','500W') {}

deffunc(name,*args,**kwargs):

#输出

deffunc(name,*args,**kwargs):

·print(name,args,kwargs)d={"degree":"primary school"}func("peiqi",d)func("peiqi",*d)func("peiqi",**d)#输出peiqi ({'degree':'primary school'},) {}peiqi ('degree',) {}peiqi () {'degree':'primary school'}

2.5 参数收集的逆过程

params=(1,2)

#输出

3

defhello_1(greeting,name):

print('%s，%s'%(greeting,name))params={'greeting':"Sir","name":"well met!"}hello_1(**params)

#输出

Sir，well met!

defwith_stars(**kwds):

print(kwds['name'],'is',kwds['age'],'years old.')

defwithout_stars(kwds):

print(kwds['name'],'is',kwds['age'],'years old.')

args={'name':'Mr,Gumby','age':42}

with_stars(**args)without_stars(args)

#输出

Mr,Gumbyis42years old.Mr,Gumbyis42years old.

• 发表于:
• 原文链接：http://kuaibao.qq.com/s/20180125G0ZJ9G00?refer=cp_1026

2019-02-23

2019-02-23

2019-02-23

2019-02-23

2019-02-23

2019-02-23