#=========================================
#第四章的python程序
#=========================================#=========================================
#4.1 簡潔的Python
#=========================================#<程序:Python數組各元素加1>
arr = [0,1,2,3,4]
for e in arr:tmp=e+1print (tmp)#==================================================================================================#=========================================
#4.2 Python內置數據結構
#=========================================#+++++++++++++++++++++++++++++++++++++++++
#4.2.1 Python基本數據類型
#+++++++++++++++++++++++++++++++++++++++++#<程序:產生10-20的隨機浮點數>
import random
f = random.uniform(10,20)
print(f)#<程序:產生10-20的隨機整數>
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)#<程序:字符串專用方法調用>
L=[1,1.3,"2","China",["I","am","another","list"]]
L.append("Hello world!")
print(L)#<程序:while循環對列表進行遍歷>
L = [1,3,5,7,9,11]
mlen = len(L)
i =0
while(i<mlen):print(L[i]+1)i += 1#<程序:for循環對列表進行遍歷>
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)——類似數據庫的結構
#+++++++++++++++++++++++++++++++++++++++++#<程序:統計字符串中各字符出現次數>
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: #還沒出現過mdict[e]=1else: #出現過mdict[e]+=1
for key,value in mdict.items():print (key,value)#練習題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'])#練習題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 擴展序列賦值
#+++++++++++++++++++++++++++++++++++++++++#<程序:擴展序列賦值語句>
i,*j=range(3)
print(i,j)#+++++++++++++++++++++++++++++++++++++++++
#4.3.4 多目標賦值
#+++++++++++++++++++++++++++++++++++++++++#<程序:多目標賦值語句1>
i=j=k=3
print(i,j,k)
i=i+2 #改變i的值,并不會影響到j, k
print(i,j,k)#<程序:多目標賦值語句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 增強賦值語句
#+++++++++++++++++++++++++++++++++++++++++#<程序:增強賦值語句1>
i=2
i*=3 #等價于i=i*3
print(i)#<程序:增強賦值語句2>
L=[1,2]; L1=L; L+=[4,5]
print(L,L1)#<程序:增強賦值語句3>
L=[1,2]; L1=L; L=L+[4,5]
print(L,L1)#==================================================================================================#=========================================
#4.4 Python控制結構
#=========================================#+++++++++++++++++++++++++++++++++++++++++
#4.4.1 if語句
#+++++++++++++++++++++++++++++++++++++++++#<程序:if語句實現百分制轉等級制>
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語句舉例—擴展>
def if_test(score):if(score>=90):print('Excellent',end=' ')if(score>=95):print('*')else:print(' ')
if_test(98)#+++++++++++++++++++++++++++++++++++++++++
#4.4.2 While循環語句
#+++++++++++++++++++++++++++++++++++++++++#<程序:while循環實現從大到小輸出2*x,0<x<=10 >
x=10
while x>0:print(2*x,end=' ')x=x-1#<程序:while循環實現從大到小輸出2*x,x不是3的倍數>
x=10
while x>0:if x%3 == 0:x=x-1continueprint(2*x,end=' ')x=x-1#<程序:while循環實現從大到小輸出2*x,x第一次為6的倍數時退出循環>
x=10
while x>0:if x%6 == 0:breakprint(2*x,end=' ')x=x-1#<程序:while循環例子1改進>
i = 1
while True:print(i,'printing')if i==2:breaki=i+1#<程序:判斷是否為質數>
b=7
a=b//2
while a>1:if b%a==0:print('b is not prime')breaka=a-1
else: #沒有執行break,則執行elseprint('b is prime')#+++++++++++++++++++++++++++++++++++++++++
#4.4.3 for循環語句
#+++++++++++++++++++++++++++++++++++++++++#<程序:for的目標<target>變量>
i=1
m=[1,2,3,4,5]
def func():x=200for x in m:print(x);print(x);
func ()#<程序:while循環改變列表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函數調用
#=========================================#+++++++++++++++++++++++++++++++++++++++++
#4.5.1 列表做參數
#+++++++++++++++++++++++++++++++++++++++++#<程序:列表的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]內容是在棧的外面,heap上return(L) # 傳回指針指到[3,2,1]。這個[3,2,1]內容不會隨F1結束而消失。
L=F1()
print("L=",L)#<程序: L做函數參數傳遞>
def F2(L): #參數L是個指針,是存在棧上的局部變量L=[2,1] #L 指向一個全新的內容,和原來的參數L完全分開了。return(L)
def F3(L): #參數L是個指針,是存在棧上的局部變量L.append(1) #L 指向的是原來的全局內容。會改變全局LL[0]=0
L= [3, 2, 1]
L=F2(L);print("L=",L)
F3(L);print("L=",L)#<程序: list為參數的遞歸函數>
def recursive(L): if L ==[]: return L=L[0:len(L)-1] # L指向新產生的一個list,和原來的List完全脫鉤了print("L=",L) recursive(L) print("L:",L) return
X=[1,2,3]
recursive(X)
print("outside recursive, 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自定義數據結構
#=========================================#+++++++++++++++++++++++++++++++++++++++++
#4.6.2 面向對象基本概念——類(Class)與對象(Object)
#+++++++++++++++++++++++++++++++++++++++++#<程序:自定義學生student類,并將該類實例化>
class student: #學生類型:包含成員變量和成員函數def __init__ (self,mname,mnumber):#當新對象object產生時所自動執行的函數self.name = mname #self代表這個object。名字self.number = mnumber #ID號碼self.Course_Grade = {} #字典存課程和其分數self.GPA = 0 #平均分數def getInfo(self):print(self.name,self.number)
XiaoMing = student("XiaoMing","1")
#每一個學生是一個object,參數給__init()__
A_Zhen = student("A_Zhen","2")
XiaoMing.getInfo()
A_Zhen.getInfo()#==================================================================================================#=========================================
#4.7 基于Python面向對象編程實現數據庫功能
#=========================================#+++++++++++++++++++++++++++++++++++++++++
#4.7.1 Python面向對象方式實現數據庫的學生類
#+++++++++++++++++++++++++++++++++++++++++#<程序:擴展后的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 #總學分數更新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面向對象方式實現數據庫的課程類
#+++++++++++++++++++++++++++++++++++++++++#<程序:課程類>
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創建數據庫的學生與課程類組
#+++++++++++++++++++++++++++++++++++++++++#<程序:建立課程信息>
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: #每一個學生修幾門課CourseNum = random.randint(3,len(CourseList)) #修CourseNum數量的課#隨機選,返回列表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 小烏龜繪制基礎圖形繪制
#+++++++++++++++++++++++++++++++++++++++++#<程序:繪出三條不同的平行線>
from turtle import *
def jumpto(x,y): #移動小烏龜不繪圖up(); goto(x,y); down()
reset() #置小烏龜到原點處
colorlist = ['red','green','yellow']
for i in range(3):jumpto(-50,50-i*50);width(5*(i+1));color(colorlist[i]) #設置小烏龜屬性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() #程序練習題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()
?