PYTHON-函數的定義與調用,返回值,和參數-練習


# day10函數的定義調用和參數作業
# 1、寫函數,用戶傳入修改的文件名、與要修改的內容,執行函數,完成批量修改操作
# def modify_file(filename,old,new):
# import os
# with open(filename,mode='rt',encoding='utf-8') as read_f,\
# open('.db.txt.swap',mode='wt',encoding='utf-8') as wrife_f:
# for line in read_f:
# wrife_f.write(line.replace(old,new))
# os.remove(filename)
# os.rename('.db.txt.swap',filename)
#
# modify_file('db.txt','sb','kevin')

# 2、寫函數,計算傳入字符串中【數字】、【字母】、【空格] 以及 【其他】的個數
# def check_list(msg):
# res={
# 'num':0,
# 'string':0,
# 'space':0,
# 'others':0
# }
# for line in msg:
# if line.isdigit():
# res['num'] += 1
# elif line.isalpha():
# res['string'] += 1
# elif line.isspace():
# res['space'] += 1
# else:
# res['others'] += 1
# return res
#
# res=check_list('hello12 342: 1213')
# print(res)

# 3、寫函數,判斷用戶傳入的對象(字符串、列表、元組)長度是否大於5。
# def check_list(msg):
# if len(msg)>5:
# print('是')
# else:
# print('否')
# msg=check_list((1,2,[1,2,4,5,5,6]))

# 4、寫函數,檢查傳入列表的長度,如果大於2,那么僅保留前兩個長度的內容,並將新內容返回給調用者。
# def check_list(msg):
# if len(msg)>2:
# msg= msg[0:2]
# return(msg)
# print(check_list([1,2,3,4,5]))

# 5、寫函數,檢查獲取傳入列表或元組對象的所有奇數位索引對應的元素,並將其作為新列表返回給調用者。
# def check_list(msg):
# return msg[::2]
# print(check_list([1,2,3,4,5,6,7]))

# 6、寫函數,檢查字典的每一個value的長度,如果大於2,那么僅保留前兩個長度的內容,並將新內容返回給調用者。
# dic = {"k1": "v1v1", "k2": [11,22,33,44]}
# PS:字典中的value只能是字符串或列表
# def check_list(dic):
# for k,v in dic.items():
# if len(v)>2:
# dic[k]=v[0:2]
# return dic
# print(check_list({'k1':'abcdef','k2':[1,2,3,4],'k3':('a','b','c')}))


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM