写简单函数---练习

 2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
 1 def fun(s):
 2     num = 0
 3     zimu = 0
 4     kongge = 0
 5     default = 0
 6     for i in s:
 7         if i.isdigit():
 8             num+=1
 9         elif i.isalpha():
10             zimu+=1
11         elif i.isspace():
12             kongge+=1
13         else:
14             default+=1
15     return num,zimu,kongge,default
16 print(fun('d  ffgh,546'))
View Code
3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
1 def length(s):
2     if len(s)>5:
3         return True
4     else:
5         return False
6 print(length('abcdef'))
7 print(length([1,2,5,3]))
8 print(length((1,'as',[11,22])))
View Code
4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
1 def fun(l):
2     if len(l)>2:
3         return l[0:2]
4     else:
5         return l
6 print(fun([11,22,33,44,55]))
View Code
5、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
1 def func(l):
2     new1=l[1::2]
3     return new1
4 print(func(['a','b',11,'cc']))
View Code
原文地址:https://www.cnblogs.com/haiyan123/p/7240722.html