# 定义一个函数,只是定义不会执行# 1.def 关键字,后跟一个空格# 2.函数名,自定义时,需遵循命名规则,大驼峰命名只给类用# 3.后面扩后和冒号不能省,括号内可以有参数# 4.函数内部所有代码缩进deffunc():print("I'm a function.")print("I will do something.")print("I done.")# 函数的调用,直接函数名后面跟括号
func()
# 参数的定义和使用# 参数 person 只是一个符号,代表的是调用的时候的某一个数据# 调用的时候,会用 p 的值代替函数中所有的 persondefhello(person):print("{0},how are you?".format(person))print("Sir,if you don't answer me,I will gone.")return"I have said hi to {0},{0} don't look me.".format(person)
p ="明月"
hello(p)
# return 案例defhello(person):print("{0},how are you?".format(person))return"I have already gone."print("Sir,if you don't answer me,I will gone.")return"I have said hi to {0},{0} don't look me.".format(person)
p ="JingTen"
rst = hello(p)print(rst)
# 默认参数实例# 报名函数,需要知道学生性别defreg(name,age,gender="male"):if gender =="male":print("{0} is {1},and he is a good student.".format(name,age))else:print("{0} is {1},and she is a good student.".format(name,age))
reg("JingTen",26)
reg("xiaojing",18,"female")
# 关键字参数案例defstu(name,age,addr):print("I'm a good student.")print("I'm {0},I have {1} years old,I live in {2}.".format(name,age,addr))
n ="JingTen"
a =26
addr ="GuangZhou"
stu(n,a,addr)# 普通参数,按位置传递,需一一对应,容易出错print("\n")
stu(age=a,name=n,addr=addr)# 关键字参数,可不考虑位置
# 收集参数代码# 函数模拟一个学生进行自我介绍,但具体内容不清楚# 把 args 看成一个 list defstu(*args):print("Hello,everybody.")# type 函数的作用是监测变量的类型print(type(args))for item in args:print(item)
stu("LiuYang",19,"上海黄浦区","WangXiaojing","Single")
stu("ZhouShengsheng")print("\n")# 参数收集案例# 说明收集参数可以不带任何实参调用,此时收集参数为空 tuple
stu()
# 收集参数混合调用案列# stu 模拟一个学生的自我介绍defstu(name,age,*args,hobby="No",**kwargs):print("Hello,everybody.")print("I'm {0},I'm {1} years old.".format(name,age))if hobby =="No":print("Sorry,I don't have hobby.")else:print("My hobby is {0}".format(hobby))print("*"*40)for i in args:print(i)print("-"*40)for k,v in kwargs.items():print(k,"---",v)# 开始调用函数
name ="JingTen"
age =26
stu(name,age)
stu(name,age,hobby="photo")
stu(name,age,"Dajiaonang","Yadan",hobby="python",hobby2="JingPingMei")
# 收集参数的解包问题# - 把参数放入 list 或者 dict 中,直接报 list/dict 中的值放入收集参数# - 在 list 或者 dict 前加 * 即可解包defstu(*args):print("Hahahahaha...")for i in args:print(i)
stu("JingTen","Dajiaonang",26)print("*"*40)
l =list()
l.append("JingTen")
l.append("Dajiaonang")
l.append(26)print(l)print("*"*40)
stu(l)# 将 l 列表当成一个值传给 argsprint("*"*40)
stu(*l)# 将 l 列表解包后的值传递给 args