4道关于Python函数的练习题
生活随笔
收集整理的這篇文章主要介紹了
4道关于Python函数的练习题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.寫函數,計算傳入函數的字符串中數字、字母、以及其他的個數
def count_fuc(str):count_number=0count_a=0count_b=0for i in str:if i.isdecimal():count_number+=1elif i.isalpha():count_a+=1else:count_b+=1return print("數字:%s,字母:%s,其他:%s"%(count_number,count_a,count_b)) str="fdsfdsf322@" count_fuc(str) ### 數字:3,字母:7,其他:12.寫一個函數,此函數只接收一個參數且參數必須是列表數據類型,此函數的完成功能是返回給調用者一個字典。
eg:傳入的列表為[1,2,3,4],返回的字典為{0:1,1:2,2:3,3:4}
def fun(list1):dict1={}for i in range(len(list1)):dict1[i]=list1[i]return dict1 list1=[1,2,3,4] print(fun(list1))3.寫函數,函數接收四個參數分別是:姓名,性別,年齡,學歷,用戶通過這四個內容傳送到函數中
此函數接受這個這個內容并追加到student_messgae.txt這個文本中,支持用戶持續輸入,Q或者q退出
''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流QQ群:725638078 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' def fuc(name,sex,age,qualifications):with open("student_message.txt",encoding="utf-8",mode="a") as f:f.write("%s,%s,%s,%s\n"%(name,sex,age,qualifications)) while True:name=input("please input your name:")if name.upper()=="Q":breakelse:sex=input("please input your sex:")age = input("please input your age:")qualifications= input("please input your qualifications:")fuc(name,sex,age,qualifications)4.寫函數,用戶傳入修改的文件名,與要修改的內容,執行函數,完成整個函數的修改操作。
import os def refile(file1,oldcontent,newcontent):with open(file1,encoding="utf-8") as f,\open("new{}".format(file1),encoding="utf-8",mode="w") as f1:for line in f:content=line.replace(oldcontent,newcontent)f1.write(content)# old_content=f.read()# new_content=old_content.replace(oldcontent,newcontent)# f1.write(new_content)os.remove(file1)os.rename("new{}".format(file1),file1) refile("student_message.txt","房貸首付","沒錢")結尾給大家推薦一個非常好的學習教程,希望對你學習Python有幫助!
Python基礎入門教程推薦:更多Python視頻教程-關注B站:Python學習者
Python爬蟲案例教程推薦:更多Python視頻教程-關注B站:Python學習者
總結
以上是生活随笔為你收集整理的4道关于Python函数的练习题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python关于装饰器的练习题
- 下一篇: 关于Python中if、for、with