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 #