Python 學習實例


聲明:本文內容主要來源於中國大學MOOC嵩天老師的課程Python語言程序設計

實例1 溫度轉換

  • 攝氏度 中國等世界大多數國家使用,以1個標準大氣壓下水的結冰點爲0度,沸點爲100度,將溫度進行等分刻畫
  • 華氏度 美國、英國等國家使用,以1個標準大氣壓下水的結冰點爲32度,沸點爲212度,將溫度進行等分刻畫

計算公式

攝氏度用C表示,華氏度用F表示

F=1.8C+32
C=(F32)/1.8

TempStr=input("請輸入帶有符號的溫度值:")
if TempStr[-1] in ('c','C'):
    ff=eval(TempStr[0:-1])*1.8 +32
    print("轉換後的溫度值是:{:.2f}".format(ff))
elif TempStr[-1] in ('f','F'):
    cc=(eval(TempStr[0:-1])-32)/1.8
    print("轉換後的溫度值是:{:.2f}".format(cc))
else:
    print("輸入格式有誤")

注:
- eval(<字符串或字符串變量>) 去掉參數最外側引號並執行餘下語句的函數
- eval(‘print(“HelloWorld!”)’)–right
- eval(“print(‘HelloWorld!’)”)–right
- eval(“print(“HelloWorld!”)”)–error


實例2 繪製蟒蛇

引入turtle(海龜)庫,turtle繪圖體系的Python實現。
turtle繪圖體系:1969年誕生,主要用於程序設計入門
Python語言的標準庫之一,入門級的圖形繪製函數庫

#PythonDraw.py
import turtle
turtle.setup(650,350,200,200) 
turtle.penup()
turtle.fd(-250)
turtle.pendown()
turtle.pensize(25)
turtle.pencolor("purple")
turtle.seth(-40)
for i in range(4):
    turtle.circle(40,80)
    turtle.circle(-40,80)
turtle.circle(40,80/2)
turtle.fd(40)
turtle.circle(16,180)
turtle.fd(40*2/3)
turtle.done()

turtle庫學習要點
- turtle.setup(width,height,startx,starty) #設置窗體大小及位置,後兩個參數可選,setup()函數不是必須的
- turtle.goto(x,y) 去哪個座標點位置
- turtle.forward(d) <=> turtle.fd(d) 向前走d個單位
- turtle.backward(d) <=> turtle.bk(d) 向後走d個單位
- turtle.circle(r,extent=None) 根據半徑r繪製extent角度的弧形
- turtle.penup() <=> turtule.pu() 擡起畫筆,海龜在飛行
- turtle.pendown() <=> turtle.pd()落下畫筆,海龜在爬行
- turtle.pensize(width) <=> turtle.width(width) 畫筆寬度,海龜的腰圍
- turtle.pencolor(color) color 爲顏色字符串或r,g,b值,畫筆演示,海龜在塗裝
- turtle.setheading(angle) <=> turtle.seth(angle) 改變海龜行進方向但不行進 angle爲絕對度數
- turtle.left(angle) 海龜行進方向向左旋轉angle度數
- turtle.right(angle) 海龜行進方向向右旋轉angle度數

實例3 天天向上的力量

基本問題:持續的價值
一年365天,每天進步1%,累計進步多少 => 1.01^365
一年365天,每天退步1%,累計剩下多少 => 0.99^365
三天打魚兩天曬網,雙休日又不退步

#DaydayUp.py
dayup=pow(1.01,365)
daydown=pow(0.99,365)
print("向上:{:.2f},向下:{:.2f}".format(dayup,daydown))

工作日模式:工作日努力1%,休息日退步1%

#WorkDayHard
dayup=1.0
dayfactor=0.01
for i in range(365):
    if i%7 in [6,0]:
        dayup=dayup*(1-dayfactor)
    else:
        dayup=dayup*(1+dayfactor)
print("WorkDay's Hard:{:.2f}".format(dayup))   

工作日模式要努力到什麼程度,才能與每天努力1%一樣
- 比較兩種模式,當努力結果一致時,輸出程度值(”笨方法”試錯)

#Same as 1%'s EveryDayHard
def dayUp(df):
    dayup=1
    for i in range(365):
        if i%7 in [0,6]:
            dayup=dayup*(1-0.01)
        else:
            dayup=dayup*(1+df)
    return dayup
dayfactor=0.01
while dayUp(dayfactor)<37.78:
    dayfactor+=0.001
print("WorkDay's Hard:{:.3f}".format(dayfactor))

實例4 文本進度條

  • 採用字符串方式打印可以動態變化的文本進度條
  • 進度條需要能在一行中逐漸變化
  • 採用sleep() 模擬一個持續的進度
#TextProBarV1.py
import time
scale=10
print("執行開始".center(16,'-'))
for i in range(scale+1):
    a='*'*i
    b='.'*(scale-i)
    c=(i/scale)*100
    print("{:^3.0f}%[{}->{}]".format(c,a,b))
print("執行結束".center(16,'-'))

>>>
------執行開始------
 0 %[->..........]
10 %[*->.........]
20 %[**->........]
30 %[***->.......]
40 %[****->......]
50 %[*****->.....]
60 %[******->....]
70 %[*******->...]
80 %[********->..]
90 %[*********->.]
100%[**********->]
------執行結束------
  • 文本進度條單行動態刷新
  • 刷新的本質是:用後打印的字符覆蓋之前的字符
  • 不能換行:print() 需要被控制
  • 要能回退:打印後光標回退到之前的位置 \r
#TextProBarV2.py
import time
for i in range(101):
    print("\r{:3}%".format(i),end="")
    time.sleep(0.1)
#TextProBarV3.py
import time
scale=50
print("執行開始".center(16,'-'))
start= time.perf_counter()
for i in range(scale+1):
    a='*'*i
    b='.'*(scale-i)
    c=(i/scale)*100
    dur=time.perf_counter()-start
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end='')
    time.sleep(0.1)
print("\n"+"執行結束".center(16,'-'))

進度條擴展
- 在任何運行時間需要較長的程序中增加進度條
- 在任何希望提高用戶體驗的應用中增加進度條

實例5 圓周率的計算

  • 近似計算公式
    π=k=0[116k(48k+128k+418k+518k+6)]

蒙特卡羅方法

#CalPiV1.py
pi=0
N=100
for k in range(N):
    pi+=1/pow(16,k)*(\
    4/(8*k+1)-2/(8*k+4)-\
    1/(8*k+5)-1/(8*k+6))
print("圓周率值是:{}".format(pi))

#CalPiV2.py
from random import random
from time import perf_counter
DARTS = 1000*1000
hits = 0.0
start = perf_counter()
for i in range(1, DARTS+1):
    x, y = random(), random()
    dist = pow(x ** 2 + y ** 2, 0.5)
    if dist <= 1.0:
        hits = hits + 1
pi = 4 * (hits/DARTS)
print("圓周率值是: {}".format(pi))
print("運行時間是: {:.5f}s".format(perf_counter() - start))

實例7 七段數碼管繪製

七段數碼管顯示圖

問題分析
- 用python繪製數碼管,似乎很有趣,該怎麼做?
- turtle 繪圖體系,time庫

基本思路
- 繪製單個數字的數碼管
- 獲得一串數字,繪製對應的數碼管
- 獲得當前系統時間,繪製對應數碼管

7.1 繪製單個數字數碼管

import turtle,time
def drawLine(draw): #繪製單段數碼管
    turtle.pendown() if draw else turtle.penup()
    turtle.fd(40)
    turtle.right(90)
def drawDigit(digit):#根據數字繪製七段數碼管
    drawLine(True) if digit in [2,3,4,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,3,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,6,8] else drawLine(False)
    turtle.left(90)
    drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False)
    drawLine(True) if digit in [0,2,3,4,5,6,7,8,9] else drawLine(False)
    drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False)
    turtle.left(180) #爲繪製後續數字確定位置
    turtle.penup() 
    turtle.fd(20)  

7.2 獲取數字繪製多個數碼管

#續7.1代碼塊
def drawDate(date):#獲取要輸出的數字
    for i in date:
        drawDigit(eval(i))#通過eval()函數將數字變爲整數
def main():
    turtle.setup(800,350,200,200)
    turtle.penup()
    turtle.fd(-300)
    turtle.pensize(5)
    drawDate('20180518')
    turtle.hideturtle()
    turtle.done()
main()

7.3以上代碼效果圖

繪製漂亮的數碼管
- 在七段數碼管之間添加線條間隔
- 獲取系統時間,增加年月日標記,並且顏色不同

def drawGap():#繪製數碼管間隔
    turtle.penup()
    turtle.fd(5)
def drawLine(draw): #繪製單段數碼管
    drawGap() #新增線條間隔
    turtle.pendown() if draw else turtle.penup()
    turtle.fd(40)
    drawGap() #新增線條間隔
    turtle.right(90)
def drawDate(date): 
    turtle.pencolor("red")
    for i in date:
        if i=='-':
            turtle.write('年',font=("Arial",18,"normal"))
            turtle.pencolor("green")
            turtle.fd(40)
        elif i=='=':
            turtle.write('月',font=("Arial",18,"normal"))
            turtle.pencolor("blue")
            turtle.fd(40)
        elif i=='+':
            turtle.write('日',font=("Arial",18,"normal"))
        else:
            drawDigit(eval(i))
def main():
    turtle.setup(800,350,200,200)
    turtle.penup()
    turtle.fd(-300)
    turtle.pensize(5)
    drawDate(time.strftime('%Y-%m=%d+',time.gmtime()))
    turtle.hideturtle()
    turtle.done()
main()

7.4效果圖

舉一反三 理解方法思維
- 模塊化思維:確定模塊接口,封裝功能
- 規則化思維:抽象過程爲規則,計算機自動執行
- 化繁爲簡:將大功能變爲小功能組合,分而治之

實例問題擴展
- 繪製帶小數點的七段數碼管
- 帶刷新的時間倒計時效果
- 繪製高級的數碼管

7.5繪製高級數碼管

實例8 科赫雪花小包裹

科赫雪花是一種高大上的分形幾何,分形幾何是一種迭代的幾何圖形,廣泛存在於自然界中
科赫曲線也叫雪花曲線。

8.1科赫曲線

  • 科赫雪花的繪製
#KochDraw.py
import turtle
def koch(size, n):
    if n == 0:
        turtle.fd(size)
    else:
        for angle in [0, 60, -120, 60]:
            turtle.left(angle)
            koch(size/3, n-1)
def main():
    turtle.setup(800,400)
    turtle.penup()
    turtle.goto(-300, -50)
    turtle.pendown()
    turtle.pensize(2)
    level=3 # 3階科赫曲線長度,階數
    koch(400,level)
    turtle.right(120)
    koch(400,level)
    turtle.right(120)
    koch(400,level)
    turtle.hideturtle()
main()

舉一反三
- 修改分形幾何繪製階數,修改旋轉角度
- 修改繪製科赫雪花的基礎框架圖形,康托爾集、謝爾賓斯基三角形,門格海綿
- 龍形曲線、空間填充曲線、科赫曲線…

實例10 文本詞頻統計

問題分析
- 英文文本 :以Hamet 爲樣本分析詞頻
- 中文文本: 以三國演義爲樣本分析人物出場次數

Hamlet 英文詞頻統計

def getText():
    txt=open('hamlet.txt','r').read()
    txt=txt.lower()
    for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt=txt.replace(ch,"")
    return txt
hamletTxt=getText()
words=hamletTxt.split()
counts={}
for word in words:
    counts[word]=counts.get(word,0)+1
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
#列表排序,按第二列由大到小排,reverse默認爲False是由小到大。
for i in range(10):
    word,count=items[i]
    print("{0:<10}{1:>5}".format(word,count))
============ RESTART: C:/mysoft/Python36/MyScript/CalHamletV1.py ============
the        1137
and         963
to          736
of          669
you         546
i           540
a           527
my          513
hamlet      459
in          435

三國人物出場次數統計

#CalThreeKingdomsV2.py
import jieba
excludes = {"將軍","卻說","荊州","二人","不可","不能","如此","商議","如何","主公","軍士","引兵","軍馬","次日","左右","大喜","東吳","不敢","今日","天下","於是","魏兵","陛下","一人","都督","人馬","不知","漢中","只見","衆將","蜀兵","後主","上馬","大叫","太守","此人","夫人","先主","後人","背後","城中","天子","一面","何不","大軍","忽報","先生","百姓","何故","然後","先鋒","不如", "趕來","原來","令人","江東","下馬","喊聲","正是","徐州","忽然","因此","成都","不見","未知","大敗","大事","之後","一軍","引軍","起兵","軍中","接應","進兵","大驚","可以","以爲","大怒","不得","心中","下文","一聲","追趕","糧草","曹兵","一齊","分解","回報","分付"}
txt = open("threekingdoms.txt", "r", encoding='utf-8').read()
words  = jieba.lcut(txt)
counts = {}
for word in words:
    if len(word) == 1:
        continue
    elif word == "諸葛亮" or word == "孔明曰":
        rword = "孔明"
    elif word == "關公" or word == "雲長":
        rword = "關羽"
    elif word == "玄德" or word == "玄德曰":
        rword = "劉備"
    elif word == "孟德" or word == "丞相":
        rword = "曹操"
    else:
        rword = word
    counts[rword] = counts.get(rword,0) + 1
for word in excludes:
    del counts[word]
items = list(counts.items())
items.sort(key=lambda x:x[1], reverse=True) 
for i in range(20):
    word, count = items[i]
    print ("{0:<10}{1:>5}".format(word, count))

上述代碼運行中可能會報一個錯
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xc8 in position 0: invalid continuation byte
把threekingdoms.txt文檔另存爲UTF-8 編碼就OK了。

    曹操    1451 
    孔明    1383 
    劉備    1252 
    關羽     784 
    張飛     358 
    呂布     300 
    趙雲     278 
    孫權     264 
   司馬懿     221 
    周瑜     217 
    袁紹     191 
    馬超     185 
    魏延     180 
    黃忠     168 
    姜維     151 
    馬岱     127 
    龐德     122 
    孟獲     122 
    劉表     120 
   夏侯惇     116 

應用問題擴展
- 四大名著…
- 政府工作報告、科研論文、新聞報道…
- 進一步還有未來詞雲…

實例11 自動軌跡繪製

自動軌跡繪製
- 需求:根據數據腳本來繪製圖形
- 不是寫代碼而是寫數據繪製軌跡
- 數據腳本是自動化最重要的第一步

自動軌跡繪製

基本思路
- 定義數據文件格式(接口)
- 編寫程序,根據文件接口解析參數繪製圖形
- 編制數據文件

數據接口定義

數據接口定義

#AutoTraceDraw.py
import turtle as t
t.title('自動軌跡繪製')
t.setup(800,600,0,0)
t.pencolor('red')
t.pensize(5)
#數據讀取
datals=[]
f=open("data.txt")
for line in f:
    line=line.replace('\n','')
    datals.append(list(map(eval,line.split(','))))
f.close()
#自動繪製
for i in range(len(datas)):
    t.pencolor(datals[i][3],datals[i][4],datals[i][5])
    t.fd(datals[i][0])
    if datals[i][1]:
        t.right(datals[i][2])
    else:
        t.left(datals[i][2])        
  • 注:map(func,list) map爲python內置函數,作用是對組合類型參數list的每一個元素都執行一次參數func對應的函數功能

舉一反三
- 自動化思維 數據和功能分離,數據驅動的自動運行
- 接口化設計 格式化設計接口,清晰明瞭
- 二維數據應用 應用維度組織數據,二維數據最常用

應用問題擴展
- 擴展接口設計,增加更多控制接口 如畫筆顏色,粗細,位置跳轉等
- 擴展功能設計,增加弧形等更多功能
- 擴展應用需求,發展自動軌跡繪製到動畫繪製

實例12 政府工作報告詞雲

問題分析
- 需求:如何直觀理解政府工作報告等政策文件
- 體會直觀的價值:生成詞雲&優化詞雲

分析材料
- 習大大在十九大的報告<<[決勝全面建成小康社會 奪取新時代中國特色社會主義偉大勝利](https://python123.io/resources/pye/新時代中國 特色社會主義.txt)>>
- 2018一號文件<<中共中央 國務院關於實施鄉村振興戰略的意見>>

基本思路
- 讀取文件、分詞整理
- 設置並輸出詞雲
- 觀察結果,優化迭代

注:下載後的txt文件需保存爲utf-8格式,否則代碼會報錯

import jieba
import wordcloud
from scipy.misc import imread
mask = imread("chinamap.jpg")
#mask = imread("fivestar.jpg")
f = open("新時代中國特色社會主義.txt","r",encoding="utf-8")
#f = open("關於實施鄉村振興戰略的意見.txt","r",encoding="utf-8")
t = f.read()
f.close()
ls = jieba.lcut(t)
txt = " ".join(ls)
w = wordcloud.WordCloud(font_path="C:\\Windows\\fonts\\msyh.ttf",width=1000,height=700,background_color="white",mask=mask)
w.generate(txt)
w.to_file("grwordcloud.png")

fivestar.jpg

chinamap.jpg

安裝 Scipy庫
- 下載Scipy依賴有mkl的numpy庫numpy-1.14.3+mkl-cp36-cp36m-win_amd64.whl
- 下載Windows二進制文件Python擴展包scipy-1.1.0-cp36-cp36m-win_amd64.whl
- 電腦中python3.6版本對應下載cp36的包
- 以管理員身份啓動命令行窗口
pip install <下載路徑>\numpy-1.14.3+mkl-cp36-cp36m-win_amd64.whl
pip install <下載路徑>\scipy-1.1.0-cp36-cp36m-win_amd64.whl

安裝scipy

ChinaMapWordCloud

實例13 體育競技分析

體育競技:高手過招,勝負只在毫釐之間

問題分析
- 毫釐是多少?如何科學分析體育競技比賽?
- 輸入:球員的水平 輸出: 可預測的比賽成績
- 計算思維:抽象+自動化
- 模擬:抽象比賽過程+自動化執行N場比賽
- 當N越大時,比賽結果分析會越科學

比賽規則
- 假定 雙人擊球比賽: A&B,回合制,5局3勝
- 開始時一方先發球,直至判分,接下來勝者發球
- 球員只能在發球局得分,15分勝一局

程序整體步驟

  • 打印程序的介紹性信息
  • 獲得程序運行參數:proA,proB,n
  • 利用球員A和B的能力值,模擬n局比賽
  • 輸出球員A和B獲勝比賽的場次及概率

程序框架

from random import random
def printInfo():
    print("這個程序模擬兩個選手A和B的某種競技比賽")
    print("程序運行需要A和B的能力值(以0到1之間的小數表示)")
def getInputs():
    a = eval(input("請輸入選手A的能力值(0-1):"))
    b = eval(input("請輸入選手B的能力值(0-1):"))
    n = eval(input("模擬比賽的場次:"))
    return a,b,n
def printSummary(winsA,winsB):
    n = winsA + winsB
    print("競技分析開始:共模擬{}場比賽".format(n))
    print("選手A獲勝{}場比賽,佔比{:0.1%}".format(winsA,winsA/n))
    print("選手B獲勝{}場比賽,佔比{:0.1%}".format(winsB,winsB/n))
def simNGames(n,proA,proB):
    winsA,winsB = 0,0
    for i in range(n):
        scoreA,scoreB = simOneGame(proA,proB)
        if scoreA > scoreB:
            winsA += 1
        else:
            winsB += 1
    return winsA,winsB      
def gameOver(a,b):
    return a==15 or b==15
def simOneGame(proA,proB):
    scoreA,scoreB = 0,0
    serving = "A"
    while not gameOver(scoreA,scoreB):
        if serving == "A":
            if random() < proA:
                scoreA +=1
            else:
                serving="B"
        else:
            if random() < proB:
                scoreB += 1
            else:
                serving="A"
    return scoreA,scoreB
def main():
    printInfo()
    proA,proB,n = getInputs()
    winsA,winsB = simNGames(n, proA, proB)
    printSummary(winsA,winsB)
main()

舉一反三
- 自頂向下:分而治之 系統思維的簡化
- 自底向上:模塊化集成
- 擴展比賽參數,增加對更多能力對比情況
- 擴展比賽設計,增加對真實比賽結果預測
- 擴展分析邏輯,反向推理,用勝率推算能力。

實例14 第三方庫自動安裝腳本

問題分析
- 批量安裝第三方庫需要人工干預,能否自動安裝
- 自動執行pip逐一根據安裝需求安裝

第三方庫自動安裝腳本

庫名 用途 pip安裝指令
NumPy N維數據表示和運算 pip install numpy
Matplotlib 二維數據可視化 pip install matplotlib
PIL 圖像處理 pip install pillow
Scikit-Learn 機器學習和數據挖掘 pip install sklearn
Requests HTTP協議訪問及網絡爬蟲 pip install requests
Jieba 中文分詞 pip install jieba
Beautiful Soup HTML和XML解析器 pip install beautifulsoup4
Wheel Python第三方庫文件打包工具 pip install wheel
PyInstaller 打包Python源文件爲可執行文件 pip install pyinstaller
Django Python最流行的Web開發框架 pip install django
Flask 輕量級Web開發框架 pip install flask
WeRoBot 微信機器人開發框架 pip install werobot
SymPy 數學符號計算工具 pip install sympy
Pandas 高效數據分析和計算 pip install pandas
Networkx 複雜網絡和圖結構的建模和分析 pip install networkx
PyQt5 基於Qt的專業級GUI開發框架 pip install pyqt5
PyOpenGL 多平臺OpenGL開發接口 pip install pyopengl
PyPDF2 PDF文件內容提取及處理 pip install pypdf2
docopt Python命令行解析 pip install docopt
PyGame 簡單小遊戲開發框架 pip install pygame
import os
libs = {"numpy","matplotlib","pillow","sklearn","requests",\
        "jieba","beautifulsoup4","wheel","networkx","sympy",\
        "pyinstaller","django","flask","werobot","pyqt5",\
        "pandas","pyopengl","pypdf2","docopt","pygame"}
try:
    for lib in libs:
        os.system("pip3 install "+lib)
    print("Successful")        
except:
    print("Failed Somehow")

實例15 霍蘭德人格分析雷達圖

雷達圖 是多特性直觀展示的重要方式

Radar Chart

霍蘭德人格分析
- 霍蘭德認爲:人格興趣與職業之間應有一種內在的對應關係
- 人格分類:研究型、藝術型、社會型、企業型、傳統型、現實型
- 職業:工程師、實驗員、藝術家、推銷員、記事員、社會工作者

問題分析
- 需求:雷達圖方式驗證霍蘭德人格分析
- 輸入:各職業人羣結合興趣的調研數據
- 通用雷達圖繪製:matplotlib庫
- 專業多維數據表示:numpy 庫
- 輸出:雷達圖

#HollandRadarDraw
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='SimHei'
radar_labels = np.array(['研究型(I)','藝術型(A)','社會型(S)',\
                         '企業型(E)','常規型(C)','現實型(R)']) #雷達標籤
nAttr = 6
data = np.array([[0.40, 0.32, 0.35, 0.30, 0.30, 0.88],
                 [0.85, 0.35, 0.30, 0.40, 0.40, 0.30],
                 [0.43, 0.89, 0.30, 0.28, 0.22, 0.30],
                 [0.30, 0.25, 0.48, 0.85, 0.45, 0.40],
                 [0.20, 0.38, 0.87, 0.45, 0.32, 0.28],
                 [0.34, 0.31, 0.38, 0.40, 0.92, 0.28]]) #數據值
data_labels = ('藝術家', '實驗員', '工程師', '推銷員', '社會工作者','記事員')
angles = np.linspace(0, 2*np.pi, nAttr, endpoint=False)
data = np.concatenate((data, [data[0]]))
angles = np.concatenate((angles, [angles[0]]))
fig = plt.figure(facecolor="white")
plt.subplot(111, polar=True)
plt.plot(angles,data,'o-', linewidth=1, alpha=0.2)
plt.fill(angles,data, alpha=0.25)
plt.thetagrids(angles*180/np.pi, radar_labels,frac = 1.2)
plt.figtext(0.52, 0.95, '霍蘭德人格分析', ha='center', size=20)
legend = plt.legend(data_labels, loc=(0.94, 0.80), labelspacing=0.1)
plt.setp(legend.get_texts(), fontsize='large')
plt.grid(True)
plt.savefig('holland_radar.jpg')
plt.show()

舉一反三
- 編程的目標感:尋找感興趣的目標,尋覓之
- 編程的沉浸感:尋找可實現的方法,思考之
- 編程的熟練度:練習、練習、再練習,熟練之

實例16 玫瑰花繪製

問題分析
- 需求:用Python繪製一朵玫瑰花,獻給所思所念
- 輸入:想象力
- 輸出:玫瑰花

#RoseDraw.py
import turtle as t
# 定義一個曲線繪製函數
def DegreeCurve(n, r, d=1):
    for i in range(n):
        t.left(d)
        t.circle(r, abs(d))
# 初始位置設定
s = 0.2 # size
t.setup(450*5*s, 750*5*s)
t.pencolor("black")
t.fillcolor("red")
t.speed(100)
t.penup()
t.goto(0, 900*s)
t.pendown()
# 繪製花朵形狀
t.begin_fill()
t.circle(200*s,30)
DegreeCurve(60, 50*s)
t.circle(200*s,30)
DegreeCurve(4, 100*s)
t.circle(200*s,50)
DegreeCurve(50, 50*s)
t.circle(350*s,65)
DegreeCurve(40, 70*s)
t.circle(150*s,50)
DegreeCurve(20, 50*s, -1)
t.circle(400*s,60)
DegreeCurve(18, 50*s)
t.fd(250*s)
t.right(150)
t.circle(-500*s,12)
t.left(140)
t.circle(550*s,110)
t.left(27)
t.circle(650*s,100)
t.left(130)
t.circle(-300*s,20)
t.right(123)
t.circle(220*s,57)
t.end_fill()
# 繪製花枝形狀
t.left(120)
t.fd(280*s)
t.left(115)
t.circle(300*s,33)
t.left(180)
t.circle(-300*s,33)
DegreeCurve(70, 225*s, -1)
t.circle(350*s,104)
t.left(90)
t.circle(200*s,105)
t.circle(-500*s,63)
t.penup()
t.goto(170*s,-30*s)
t.pendown()
t.left(160)
DegreeCurve(20, 2500*s)
DegreeCurve(220, 250*s, -1)
# 繪製一個綠色葉子
t.fillcolor('green')
t.penup()
t.goto(670*s,-180*s)
t.pendown()
t.right(140)
t.begin_fill()
t.circle(300*s,120)
t.left(60)
t.circle(300*s,120)
t.end_fill()
t.penup()
t.goto(180*s,-550*s)
t.pendown()
t.right(85)
t.circle(600*s,40)
# 繪製另一個綠色葉子
t.penup()
t.goto(-150*s,-1000*s)
t.pendown()
t.begin_fill()
t.rt(120)
t.circle(300*s,115)
t.left(75)
t.circle(300*s,100)
t.end_fill()
t.penup()
t.goto(430*s,-1070*s)
t.pendown()
t.right(30)
t.circle(-600*s,35)
t.done()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章