日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python学习实例(4)

發(fā)布時間:2023/12/13 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python学习实例(4) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#========================================= #第四章的python程序 #=========================================#========================================= #4.1 簡潔的Python #=========================================#<程序:Python數(shù)組各元素加1> arr = [0,1,2,3,4] for e in arr:tmp=e+1print (tmp)#==================================================================================================#========================================= #4.2 Python內(nèi)置數(shù)據(jù)結(jié)構(gòu) #=========================================#+++++++++++++++++++++++++++++++++++++++++ #4.2.1 Python基本數(shù)據(jù)類型 #+++++++++++++++++++++++++++++++++++++++++#<程序:產(chǎn)生10-20的隨機(jī)浮點數(shù)> import random f = random.uniform(10,20) print(f)#<程序:產(chǎn)生10-20的隨機(jī)整數(shù)> import random i = random.randint(10,20) print(i)#<程序:布爾類型例子> b = 100<101 print (b)#+++++++++++++++++++++++++++++++++++++++++ #4.2.2 列表(list) #+++++++++++++++++++++++++++++++++++++++++#<程序:序列索引> L=[1,1.3,"2","China",["I","am","another","list"]] print(L[0])#<程序:序列加法> L1= [1,1.3] L2= ["2","China",["I","am","another","list"]] L = L1 +L2 print(L)#<程序:字符串專用方法調(diào)用> L=[1,1.3,"2","China",["I","am","another","list"]] L.append("Hello world!") print(L)#<程序:while循環(huán)對列表進(jìn)行遍歷> L = [1,3,5,7,9,11] mlen = len(L) i =0 while(i<mlen):print(L[i]+1)i += 1#<程序:for循環(huán)對列表進(jìn)行遍歷> L = [1,3,5,7,9,11] for e in L:e+=1print(e)#+++++++++++++++++++++++++++++++++++++++++ #4.2.3 再談字符串 #+++++++++++++++++++++++++++++++++++++++++#第一種方式 S=input("1. Enter 1,2, , , :")#Enter: 1,2,3,4 L = S.split(sep=',') #['1','2','3','4'] X=[] for a in L:X.append(int(a)) print("Use split:", X)#第二種方式 S=input("2. Enter 1,2, , , :")#Enter: 1,2,3,4 L = S.split(sep=',') #['1','2','3','4'] L= [int(e) for e in L] print("Use split and embedded for:", L)#+++++++++++++++++++++++++++++++++++++++++ #4.2.4 字典(Dictionary)——類似數(shù)據(jù)庫的結(jié)構(gòu) #+++++++++++++++++++++++++++++++++++++++++#<程序:統(tǒng)計字符串中各字符出現(xiàn)次數(shù)> mstr = "Hello world, I am using Python to program, it is very easy to implement." mlist = list(mstr) mdict = {} for e in mlist:if mdict.get(e,-1)==-1: #還沒出現(xiàn)過mdict[e]=1else: #出現(xiàn)過mdict[e]+=1 for key,value in mdict.items():print (key,value)#練習(xí)題4.2.13#程序1 d_info1={'XiaoMing':[ 'stu','606866'],'AZhen':[ 'TA','609980']} print(d_info1['XiaoMing']) print(d_info1['XiaoMing'][1])#程序2 d_info2={'XiaoMing':{ 'role': 'stu','phone':'606866'}, 'AZhen':{ 'role': 'TA','phone':'609980'}} print(d_info2['XiaoMing']) print(d_info2['XiaoMing']['phone'])#練習(xí)題4.2.14#程序1 di={'fruit':['apple','banana']} di['fruit'].append('orange') print(di)#程序2 D={'name':'Python','price':40} D['price']=70 print(D) del D['price'] print(D)#程序3 D={'name':'Python','price':40} print(D.pop('price')) print(D)#程序4 D={'name':'Python','price':40} D1={'author':'Dr.Li'} D.update(D1) print(D)#==================================================================================================#========================================= #4.3 Python賦值語句 #=========================================#+++++++++++++++++++++++++++++++++++++++++ #4.3.1 基本賦值語句 #+++++++++++++++++++++++++++++++++++++++++#<程序:基本賦值語句> x=1; y=2 k=x+y print(k)#+++++++++++++++++++++++++++++++++++++++++ #4.3.2 序列賦值 #+++++++++++++++++++++++++++++++++++++++++#<程序:序列賦值語句> a,b=4,5 print(a,b) a,b=(6,7) print(a,b) a,b="AB" print(a,b) ((a,b),c)=('AB','CD') #嵌套序列賦值 print(a,b,c)#+++++++++++++++++++++++++++++++++++++++++ #4.3.3 擴(kuò)展序列賦值 #+++++++++++++++++++++++++++++++++++++++++#<程序:擴(kuò)展序列賦值語句> i,*j=range(3) print(i,j)#+++++++++++++++++++++++++++++++++++++++++ #4.3.4 多目標(biāo)賦值 #+++++++++++++++++++++++++++++++++++++++++#<程序:多目標(biāo)賦值語句1> i=j=k=3 print(i,j,k) i=i+2 #改變i的值,并不會影響到j(luò), k print(i,j,k)#<程序:多目標(biāo)賦值語句2> i=j=[] #[]表示空的列表,定義i和j都是空列表,i和j指向同一個空的列表地址 i.append(30) #向列表i中添加一個元素30,列表j也受到影響 print(i,j) i=[];j=[] i.append(30) print(i,j)#+++++++++++++++++++++++++++++++++++++++++ #4.3.5 增強(qiáng)賦值語句 #+++++++++++++++++++++++++++++++++++++++++#<程序:增強(qiáng)賦值語句1> i=2 i*=3 #等價于i=i*3 print(i)#<程序:增強(qiáng)賦值語句2> L=[1,2]; L1=L; L+=[4,5] print(L,L1)#<程序:增強(qiáng)賦值語句3> L=[1,2]; L1=L; L=L+[4,5] print(L,L1)#==================================================================================================#========================================= #4.4 Python控制結(jié)構(gòu) #=========================================#+++++++++++++++++++++++++++++++++++++++++ #4.4.1 if語句 #+++++++++++++++++++++++++++++++++++++++++#<程序:if語句實現(xiàn)百分制轉(zhuǎn)等級制> def if_test(score):if(score>=90):print('Excellent')elif(score>=80):print('Very Good')elif(score>=70):print('Good')elif(score>=60):print('Pass')else:print('Fail') if_test(88)#<程序:if語句舉例—擴(kuò)展> def if_test(score):if(score>=90):print('Excellent',end=' ')if(score>=95):print('*')else:print(' ') if_test(98)#+++++++++++++++++++++++++++++++++++++++++ #4.4.2 While循環(huán)語句 #+++++++++++++++++++++++++++++++++++++++++#<程序:while循環(huán)實現(xiàn)從大到小輸出2*x,0<x<=10 > x=10 while x>0:print(2*x,end=' ')x=x-1#<程序:while循環(huán)實現(xiàn)從大到小輸出2*x,x不是3的倍數(shù)> x=10 while x>0:if x%3 == 0:x=x-1continueprint(2*x,end=' ')x=x-1#<程序:while循環(huán)實現(xiàn)從大到小輸出2*x,x第一次為6的倍數(shù)時退出循環(huán)> x=10 while x>0:if x%6 == 0:breakprint(2*x,end=' ')x=x-1#<程序:while循環(huán)例子1改進(jìn)> i = 1 while True:print(i,'printing')if i==2:breaki=i+1#<程序:判斷是否為質(zhì)數(shù)> b=7 a=b//2 while a>1:if b%a==0:print('b is not prime')breaka=a-1 else: #沒有執(zhí)行break,則執(zhí)行elseprint('b is prime')#+++++++++++++++++++++++++++++++++++++++++ #4.4.3 for循環(huán)語句 #+++++++++++++++++++++++++++++++++++++++++#<程序:for的目標(biāo)<target>變量> i=1 m=[1,2,3,4,5] def func():x=200for x in m:print(x);print(x); func ()#<程序:while循環(huán)改變列表2> words=['cat','window', 'defenestrate'] for w in words[:]:if len(w)>6:words.append(w) print(words)#<程序:使用range遍歷列表> L=['Python','is','strong'] for i in range(len(L)):print(i,L[i],end=' ')#==================================================================================================#========================================= #4.5 Python函數(shù)調(diào)用 #=========================================#+++++++++++++++++++++++++++++++++++++++++ #4.5.1 列表做參數(shù) #+++++++++++++++++++++++++++++++++++++++++#<程序:列表的append方法> def func(L1):L1.append(1) L=[2] func(L) print(L)#<程序:加法(+)合并列表> def func(L1):x=L1+[1]print(x,L1) L=[2] func(L) print (L)#<程序:列表分片的例子> def func(L1):x=L1[1:3]print(x,L1) L=[2,'a',3,'b',4] func(L) print(L)#<程序: L=X> def F0():X=[9,9] #X是局部變量,這個指針在局部棧上,但是[9,9]在外面heap上。L.append(8) #L是全局變量 X=[1,2,3] L=X F0() print("X=",X,"L=",L)#<程序: L=X[:]> def F0():X=[9,9] #X 這個指針在局部棧上,但是[9,9]在外面heap上。L.append(8) #L是全局變量 X=[1,2,3]; L=X[:] #L是X的全新拷貝 F0() #改變L不會改變X print("X=",X,"L=",L)#<程序: 返回(return)列表> def F1():L=[3,2,1] #L是局部變量,而[3,2,1]內(nèi)容是在棧的外面,heap上return(L) # 傳回指針指到[3,2,1]。這個[3,2,1]內(nèi)容不會隨F1結(jié)束而消失。 L=F1() print("L=",L)#<程序: L做函數(shù)參數(shù)傳遞> def F2(L): #參數(shù)L是個指針,是存在棧上的局部變量L=[2,1] #L 指向一個全新的內(nèi)容,和原來的參數(shù)L完全分開了。return(L) def F3(L): #參數(shù)L是個指針,是存在棧上的局部變量L.append(1) #L 指向的是原來的全局內(nèi)容。會改變?nèi)諰L[0]=0 L= [3, 2, 1] L=F2(L);print("L=",L) F3(L);print("L=",L)#<程序: list為參數(shù)的遞歸函數(shù)> def recursive(L): if L ==[]: return L=L[0:len(L)-1] # L指向新產(chǎn)生的一個list,和原來的List完全脫鉤了print("L=",L) recursive(L) print("L:",L) return X=[1,2,3] recursive(X) print("outside recursive, X=",X)#練習(xí)題4.5.2def recursive_2(L): if L ==[]: return print("L=",L) recursive_2(L[0:len(L)-1]) print("L:",L) return X=[1,2,3] recursive_2(X) print("outside recursive_2, X=",X)#==================================================================================================#========================================= #4.6 Python自定義數(shù)據(jù)結(jié)構(gòu) #=========================================#+++++++++++++++++++++++++++++++++++++++++ #4.6.2 面向?qū)ο蠡靖拍睢?Class)與對象(Object) #+++++++++++++++++++++++++++++++++++++++++#<程序:自定義學(xué)生student類,并將該類實例化> class student: #學(xué)生類型:包含成員變量和成員函數(shù)def __init__ (self,mname,mnumber):#當(dāng)新對象object產(chǎn)生時所自動執(zhí)行的函數(shù)self.name = mname #self代表這個object。名字self.number = mnumber #ID號碼self.Course_Grade = {} #字典存課程和其分?jǐn)?shù)self.GPA = 0 #平均分?jǐn)?shù)def getInfo(self):print(self.name,self.number) XiaoMing = student("XiaoMing","1") #每一個學(xué)生是一個object,參數(shù)給__init()__ A_Zhen = student("A_Zhen","2") XiaoMing.getInfo() A_Zhen.getInfo()#==================================================================================================#========================================= #4.7 基于Python面向?qū)ο缶幊虒崿F(xiàn)數(shù)據(jù)庫功能 #=========================================#+++++++++++++++++++++++++++++++++++++++++ #4.7.1 Python面向?qū)ο蠓绞綄崿F(xiàn)數(shù)據(jù)庫的學(xué)生類 #+++++++++++++++++++++++++++++++++++++++++#<程序:擴(kuò)展后的Student類> class student:def __init__ (self,mname,studentID):self.name = mname; self.StuID = studentID; self.Course_Grade = {};self.Course_ID = []; self.GPA = 0; self.Credit = 0def selectCourse(self,CourseName,CourseID):self.Course_Grade[CourseID]=0; #CourseID:0 加入字典self.Course_ID.append(CourseID) # CourseID 加入列表self.Credit = self.Credit+ CourseDict[CourseID].Credit #總學(xué)分?jǐn)?shù)更新def getInfo(self):print("Name:",self.name);print("StudentID",self.StuID);print("Course:")for courseID,grade in self.Course_Grade.items():print(CourseDict[courseID].courseName,grade)print("GPA",self.GPA); print("Credit",self.Credit); print("")def TakeExam(self, CourseID):self.Course_Grade[CourseID]=random.randint(50,100)self.calculateGPA()def Grade2GPA(self,grade):if(grade>=90):return 4elif(grade>=80):return 3elif(grade>=70):return 2elif(grade>=60):return 1else:return 0def calculateGPA(self):g = 0;#遍歷每一門所修的課程for courseID,grade in self.Course_Grade.items():g = g + self.Grade2GPA(grade)* CourseDict[courseID].Creditself.GPA = round(g/self.Credit,2)#+++++++++++++++++++++++++++++++++++++++++ #4.7.2 Python面向?qū)ο蠓绞綄崿F(xiàn)數(shù)據(jù)庫的課程類 #+++++++++++++++++++++++++++++++++++++++++#<程序:課程類> class Course:def __init__ (self,cid,mname,CourseCredit,FinalDate):self.courseID = cidself.courseName = mnameself.studentID = []self.Credit = CourseCreditself.ExamDate = FinalDatedef SelectThisCourse(self,stuID): #記錄誰修了這門課,在studentID列表里self.studentID.append(stuID)#+++++++++++++++++++++++++++++++++++++++++ #4.7.3 Python創(chuàng)建數(shù)據(jù)庫的學(xué)生與課程類組 #+++++++++++++++++++++++++++++++++++++++++#<程序:建立課程信息> def setupCourse (CourseDict): #建立CourseList: list of Course objectsCourseDict[1]=Course(1,"Introducation to Computer Science",4,1)CourseDict[2]=Course(2,"Advanced Mathematics",5,2)CourseDict[3]=Course(3,"Python",3,3)CourseDict[4]=Course(4,"College English",4,4)CourseDict[5]=Course(5,"Linear Algebra",3,5)#<程序:建立班級信息> def setupClass (StudentDict): #輸入一個空列表NameList = ["Aaron","Abraham","Andy","Benson","Bill","Brent","Chris","Daniel","Edward","Evan","Francis","Howard","James","Kenneth","Norma","Ophelia","Pearl","Phoenix","Prima","XiaoMing"] stuid = 1for name in NameList:StudentDict [stuid]=student(name,stuid) #student對象的字典stuid = stuid + 1#+++++++++++++++++++++++++++++++++++++++++ #4.7.4 Python實例功能模擬 #+++++++++++++++++++++++++++++++++++++++++#<程序:模擬選課> def SelectCourse (StudentList, CourseList):for stu in StudentList: #每一個學(xué)生修幾門課CourseNum = random.randint(3,len(CourseList)) #修CourseNum數(shù)量的課#隨機(jī)選,返回列表CourseIndex = random.sample(range(len(CourseList)), CourseNum)for index in CourseIndex:stu.selectCourse(CourseList[index].courseName,CourseList[index].Credit)CourseList[index].SelectThisCourse(stu.StuID)#<程序:模擬考試> def ExamSimulation (StudentList, CourseList):for day in range(1,6): #Simulate the datefor cour in CourseList:if(cour.ExamDate==day): # Hold the exam of course on that dayfor stuID in cour.studentID:for stu in StudentList:if(stu.StuID == stuID): #student stuID selected this coursestu.TakeExam(cour.courseID)#<程序:主程序> import random CourseDict={} StudentDict={} setupCourse(CourseDict) setupClass(StudentDict) SelectCourse(list(StudentDict.values()),list(CourseDict.values())) ExamSimulation(list(StudentDict.values()),list(CourseDict.values())) for sid,stu in StudentDict.items():stu.getInfo()#==================================================================================================#========================================= #4.8 有趣的小烏龜——Python之繪圖 #=========================================#+++++++++++++++++++++++++++++++++++++++++ #4.8.2 小烏龜繪制基礎(chǔ)圖形繪制 #+++++++++++++++++++++++++++++++++++++++++#<程序:繪出三條不同的平行線> from turtle import * def jumpto(x,y): #移動小烏龜不繪圖up(); goto(x,y); down() reset() #置小烏龜?shù)皆c處 colorlist = ['red','green','yellow'] for i in range(3):jumpto(-50,50-i*50);width(5*(i+1));color(colorlist[i]) #設(shè)置小烏龜屬性forward(100) #繪圖 s = Screen(); s.exitonclick()#<程序:繪出邊長為50的正方形> from turtle import * def jumpto(x,y):up(); goto(x,y); down() reset() jumpto(-25,-25) k=4 for i in range(k):forward(50)left(360/k) s = Screen(); s.exitonclick()#解法1#<程序:繪出半徑為50的圓> from turtle import * import math def jumpto(x,y):up(); goto(x,y); down() def getStep(r,k):rad = math.radians(90*(1-2/k))return ((2*r)/math.tan(rad)) def drawCircle(x,y,r,k):S=getStep(r,k)speed(10); jumpto(x,y) for i in range(k):forward(S)left(360/k) reset() drawCircle(0,0,50,20) s = Screen(); s.exitonclick()#解法1#<程序:繪出半徑為50的圓> from turtle import * circle(50) s = Screen(); s.exitonclick()#+++++++++++++++++++++++++++++++++++++++++ #4.8.3 小烏龜繪制迷宮 #+++++++++++++++++++++++++++++++++++++++++#<程序:迷宮輸入> m=[[1,1,1,0,1,1,1,1,1,1],[1,0,0,0,0,0,0,0,1,1],[1,0,1,1,1,1,1,0,0,1],[1,0,1,0,0,0,0,1,0,1],[1,0,1,0,1,1,0,0,0,1],[1,0,0,1,1,0,1,0,1,1],[1,1,1,1,0,0,0,0,1,1],[1,0,0,0,0,1,1,1,0,0],[1,0,1,1,0,0,0,0,0,1],[1,1,1,1,1,1,1,1,1,1]]#<程序:迷宮中的墻與通道繪制> from turtle import * def jumpto(x,y):up(); goto(x,y); down() def Access(x,y):jumpto(x,y)for i in range(4):forward(size/6); up(); forward(size/6*4); down();forward(size/6); right(90) def Wall(x,y,size):color("red"); jumpto(x,y);for i in range(4):forward(size)right(90)goto(x+size,y-size); jumpto(x,y-size); goto(x+size,y)#<程序:小烏龜畫迷宮> reset(); speed('fast') size=40; startX = -len(m)/2*size; startY = len(m)/2*size for i in range(0,len(m)):for j in range(0,len(m[i])):if m[i][j]==0:Access(startX+j*size, startY-i*size)else:Wall(startX+j*size, startY-i*size,size) s = Screen(); s.exitonclick() #程序練習(xí)題4.8.2#<程序:多個圓形的美麗聚合> from turtle import * reset() speed('fast') IN_TIMES = 40 TIMES = 20 for i in range(TIMES):right(360/TIMES)forward(200/TIMES) #這一步是做什么用的?for j in range(IN_TIMES):right(360/IN_TIMES)forward (400/IN_TIMES) write(" Click me to exit", font = ("Courier", 12, "bold") ) s = Screen() s.exitonclick()

?

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎

總結(jié)

以上是生活随笔為你收集整理的python学习实例(4)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。