TOP

python - 函数练习题

写代码,接受n个数字,求这些数字的和
1 def sum_func(*args):
2     total = 0
3     for i in args:
4         total+=i
5     return total
6 print(sum_func(1,2,3,44,5,5,87,1,25))
读代码 打印出的a,b,c分别是多少
1 a = 10
2 b = 20
3 def test5(a,b):
4     print(a,b)
5 c = test5(b,a)
6 print(c)
7 print(a)
8 print(b)
9 # c = None ,10 a = 10 b = 20
读代码 打印出的a,b,c分别是多少
 1 a = 10
 2 b = 20
 3 def test5(a,b):
 4     a = 3
 5     b = 5
 6     print(a,b)
 7 c = test5(b,a)
 8 print(c)
 9 print(a)
10 print(b)
11  # c = None a = 10 b = 20
写函数,检查获取传入的列表或者元祖的所有奇数索引对应的元素,返回回去
1 def func(l):
2     return l[1::2]
3 print(func([1,2,3,4,5,6,7,8]))
 写函数,判断用户传入的对象(列表,字符串,元祖)是否长度大于5
1 def func(l):
2     # l = [True  if len(l)> 5 else False]
3     # return l
4     return len(l)>5
5 print(func("sdsadhk"))
写函数,如果的长度大于2,仅保留两个长度内容并返回回去
1 def func(l):
2     # l = [l[0:2] if len(l)>2 else False]
3     # return l
4     return l[:2]
5 print(func("sdsadhk"))
写函数,计算传入字符串中的数字,字母,空格,以及其他的个数返回结果
1 def func(l):
2     dic = {"num":0,"alpha":0,"space":0,"other":0}
3     for i in l:
4         if    i.isdigit():dic["num"]+=1
5         elif i.isalpha():dic["alpha"]+=1
6         elif i.isspace():dic["space"]+=1
7         else:dic["other"]+=1
8     return dic
9 print(func("shdah sdkah.sdha123 ..sihdao"))
 写函数,检查用户传入的对象是否含有空内容,并返回结果
 1 def  func(x):
 2     if    type(x) is str and x :
 3         for i in x  :
 4             if i == " ":return True
 5     elif x and type(x) is list or type(x) is tuple:
 6         for i in x:
 7             if not i:return True
 8     elif not x :return True
 9     else : return True
10 print(func("shkahk shdalh"))
11 print(func([1,2," ",[],]))
12 print(func((1,2,[],)))
13 print(func([]))
写函数,检查传入字典的每个value的长度,长度大于2仅保留两个长度的内容,返回给调用者
1 def     func(dic):
2     for k in dic:
3         if len(dic[k]) > 2:
4             dic[k] = dic[k][:2]
5     return dic
6 dic = {"k2":"shdahdkl","wc":[1,2,3,4,5,6]}
7 print(func(dic))
 写函数,用户传入修改的文件名字,以及要修改的内容,
  执行函数,完成整个文件的批量修改操作
1 def func(filename,old,new):
2     with open(filename,encoding="utf-8") as f, open("%s.bak" %filename,"w",encoding="utf-8") as f2:
3         for line in f:
4             if old in line:
5                 line = line.replace(old,new)
6             f2.write(line)
7     import os
8     os.remove(filename)
9     os.rename("%s.bak" %filename,filename)

 





















posted @ 2018-09-21 16:57  羊驼之歌  阅读(699)  评论(0编辑  收藏  举报