python之初识def函数(练习题)
1 # 必做题: 2 # 1、整理函数相关知识点,画思维导图,写博客 3 # 2、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。 4 # def fuc1(user_li): 5 # new_li = [] 6 # for i in range(len(user_li)): 7 # if i % 2 == 1: 8 # new_li.append(user_li[i]) 9 # return new_li 10 # 11 # print(fuc1([2,3,3,4,2,3])) 12 # print(fuc1((2,3,2,3,42,2))) 13 14 15 # 3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。 16 17 # def fuc2(user_send): 18 # if len(user_send) > 5: 19 # print('yes! the length is greater than 5') 20 # else: 21 # print('no! try again') 22 # 23 # fuc2('safasf') 24 # fuc2([2,3,32,1]) 25 26 # 4、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。 27 28 # def fuc3(user_send): 29 # if len(user_send) > 2: 30 # return user_send[:2] 31 # else: 32 # return ("try again") 33 # result = fuc3([1,2]) 34 # print(result) 35 # 5、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数,并返回结果。 36 37 # def fuc4(user_str): 38 # digit = [] 39 # alpha = [] 40 # spacebar = [] 41 # other =[] 42 # for i in user_str: 43 # if i.isdigit(): 44 # digit.append(i) 45 # elif i.isalpha(): 46 # alpha.append(i) 47 # elif i ==' ': 48 # spacebar.append(i) 49 # else: 50 # other.append(i) 51 # return len(digit),len(alpha),len(spacebar),len(other) 52 # a,b,c,d = fuc4('asdasf asdas 123123 ,.') 53 # print('数字:',a ,' 字母:',b,'空格: ',c,'其他:' ,d) 54 55 # 6、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容,并返回结果。 56 # def fuc5(user_send): 57 # j = 0 58 # for i in user_send: 59 # if i == ' ': 60 # j += 1 61 # if j > 0: 62 # print('yes it has spacebar') 63 # else: 64 # print('no spacebar') 65 # fuc5('sfasfa asda asd') 66 # 7、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。 67 dic = {"k1": "v1v1", "k2": [11,22,33,44]} 68 # PS:字典中的value只能是字符串或列表 69 # def fuc6(user_key,user_value): 70 # if len(user_value) > 2: 71 # dic.setdefault(user_key,user_value[:2]) 72 # return dic[user_key] 73 # print(fuc6('k3','sadasd')) 74 # 8、写函数,接收两个数字参数,返回比较大的那个数字。 75 # def fuc7(num1,num2): 76 # new_num = num1 if num1 > num2 else num2 77 # return new_num 78 # print(fuc7(20,32)) 79 # 选做题: 80 # 9、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作(进阶)。 81 def fuc8(file_name,file_content): 82 f = open(file_name,'w') 83 f.write(file_content) 84 f.close() 85 86 fuc8('new_file.txt','iron maiden') 87 fuc8('new_file.txt','xxxxxxxxxxxxxxxxxx') 88 89 # 10、写一个函数完成三次登陆功能,再写一个函数完成注册功能 90 91 92 # 明日内容: 93 # 函数的动态参数:http://www.cnblogs.com/Eva-J/articles/7125925.html 94 # 函数的进阶内容:http://www.cnblogs.com/Eva-J/articles/7156261.html 95 # 96 # 默写内容: 97 # def my_len(lst): 98 # count = 0 99 # for i in lst: 100 # count+=1 101 # return count 102 # 103 # l = [1,2,3,4] 104 # len_count = my_len(l) 105 # print(len_count) 106 #