#coding=utf-8
‘’’
函数 是一小段代码 实现一个小功能
函数作用:减少代码冗余 可以相互调用 可重用
优秀的程序员 都会采用函数编程
举个栗子:星球的boss 要写一段代码去干掉星球 ;
函数定义 def 函数名(参数)
‘’’
def test():
print(1+1)
test() #调用函数 直接写函数名
test()
#函数有了参数之后 就变得更强大了
def Year(year): #形象的参数 抽象的 没有任何值
if year%40 and year%100!=0 or year%4000:
print(‘闰年’)
else:
print(‘平年’)
Year(2016) #实参 有实际的数据 2016传递给year形参
Year(2018)
Year(1900)
#多个参数
def Test1(x,y,z):
print(x+y+z)
Test1(2,3,6)#函数有多少个形参 就必须要传递多少个实参 参数的传递是按照顺序 程序自己知道
Test1(5,5,4)
#缺省参数 默认参数
def test2(x,y=6,z=5):
print(x+y+z)
test2(2,3) #默认值 就是你不传递实参的时候 就取自己的默认值
test2(1, 2, 3) #如果你传递了实际参数 那就用实际的值
#函数return 返回值 谁去调用这个函数 返回值就给谁
def test3(x,y=6,z=5):
return x+y+z
x=test3(1)
print(x)
‘’’
注意 函数默认参数不要乱写 要么全部写上 要么就写后面的
‘’’
###############################################
print(’*’*100)
#函数多个return
def test4(x,y): #x=3 y=4
if x>y:
return x+y
else:
return x-y
print(test4(3,4))
print(test4(6,5))
#函数相互调用
def test5(a,b): #a=3 b=4
a=test4(a, b) #a=test4(3,4) -1
return a+b #-1+4
print(test5(3,4)) #3
print(test5(6,5)) #16
#########################课堂练习################################
‘’’
定义一个函数 Getday(year,month,day) 传入年 月 日,返回是今年的第几天
分析题目:每个月的天数都 是固定的,除了闰年多一天
‘’’
def Getday(year,month,day):
count=0
x=[31,28,31,30,31,30,31,31,30,31,30,31] #定义平年 每个月天数列表
if year%40 and year%100!=0 or year%4000: #判断闰年
x[1]=29 #如果是闰年 就把2月天数修改成29天
for i in range(month-1): #遍历月份 当月不用遍历
count+=x[i] #把每个月的天数累加
return count+day #再加上当月的天数
print(Getday(2016, 12, 31))
print(Getday(2018, 12, 31))
‘’’
编写函数 Getcount(string) 传入一串字符串 统计字母 数字 空格 其他字符 分别是多少个?
x.isalpha()判断字母 x.isdigit()判断数字 x.isspace()判断空格
‘’’
def Getcount(string):
zimu=0;shuzi=0;kongge=0;qita=0
for x in string:
if x.isalpha():
zimu+=1
elif x.isdigit():
shuzi+=1
elif x.isspace():
kongge+=1
else:
qita+=1
return zimu,shuzi,kongge,qita
print(Getcount(‘asd2k12k31k23k1231l23 asdf a sdf as df12312a,sdf,s,adf,’))