python學習例項(1)
阿新 • • 發佈:2018-12-14
#====================================== #1.2 計算機程式設計的基本概念 #====================================== #++++++++++++++++++++++++++++++++++++++ #1.2.2 從Python語言進入計算機語言的世界 #++++++++++++++++++++++++++++++++++++++ #<程式:例子1> def F(x,y): return(x*x+y*y) print("F(2,2)=",F(2,2)) print("F(3,2)=",F(3,2)) #<程式:例子2> def Pr(): for i in range(0,10): # 索引 i = 0 to 9 print("Hello world") #在函式程式外面Pr() Pr() # 輸出 Hello world 10 遍 #<程式:布林型別例子> b = 100<101 print(b) #<程式:for迴圈例子> for i in range(1, 5): print(i) #<程式:while迴圈例子> i = 1 while i<5: print(i) i=i+1 #<程式:if語句例子> i=10 j=11 if i< j: print("i<j") else: print("i>=j") #====================================== #1.3 計算機核心知識——演算法(Algorithm) #====================================== #++++++++++++++++++++++++++++++++++++++ #1.3.2 解平方根演算法一 #++++++++++++++++++++++++++++++++++++++ #<程式:平方根運算1> def square_root_1(): #函式定義,函式名為square_root_1 c = 10 #所求平方根的輸入,即該段程式求根號10 i = 0 #記錄執行迴圈次數 g = 0 for j in range(0,c+1): #for 迴圈開始 if (j * j > c and g==0):#if 語句塊,獲取g,使得g2<c,(g+1)2>c g = j - 1 #for 迴圈結束 while (abs(g * g - c) > 0.0001):#判斷g2-c是否在精度範圍內,while迴圈 g += 0.00001 #g每次加步長,以逼近所求解 i = i+1 print ("%d:g = %.5f" % (i,g)) #函式外,執行下面的語句 square_root_1() #++++++++++++++++++++++++++++++++++++++ #1.3.3 解平方根演算法二 #++++++++++++++++++++++++++++++++++++++ #<程式:平方根運算2-二分法> def square_root_2(): i = 0 c = 10 m_max = c m_min = 0 g = (m_min+m_max)/2 while (abs(g*g -c) > 0.00000000001): #while迴圈開始 if (g*g <c): m_min = g else: m_max = g g = (m_min + m_max)/2 i = i+1 print ("%d:%.13f" % (i,g)) #while迴圈結束 #函式之外執行 square_root_2 () #++++++++++++++++++++++++++++++++++++++ #1.3.4 解平方根演算法三 #++++++++++++++++++++++++++++++++++++++ #<程式:平方根運算3-牛頓法> def square_root_3(): c = 10 g = c/2 i = 0 while abs(g*g - c) > 0.00000000001: g = (g + c/g)/2 i = i+1 print("%d:%.13f" % (i,g)) square_root_3() #====================================== #1.5 計算機前沿知識——大資料(Big Data) #====================================== #++++++++++++++++++++++++++++++++++++++ #1.5.5 對資料和邏輯的正確態度 #++++++++++++++++++++++++++++++++++++++ #<程式:求圓周率-蒙地卡羅法> import random def pi(times): sum=0 for i in range(times): x=random.random() y=random.random() d2=x*x+y*y #算到原點的距離 if d2<=1: sum+=1 #距離<=1, 代表在圓裡面。 return(sum/times*4) #函式外執行 times=100000000 x=pi(times) print("pi=%.8f"%(x))