從turtle海龜動畫 學習 Python - 高中彈性課程系列 5 用函數封裝重複性指令-呼叫函數令烏龜畫正 n 邊形

46 篇文章 1 订阅
32 篇文章 1 订阅

“Talk is cheap. Show me the code.”
― Linus Torvalds

老子第41章
上德若谷
大白若辱
大方無隅
大器晚成
大音希聲
大象無形
道隱無名

拳打千遍, 身法自然

本系列文章之連結

  • 從turtle海龜動畫學習Python-高中彈性課程1 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 2 安裝 Python, 線上執行 Python link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 3 烏龜繪圖 所需之Python基礎 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 4 烏龜開始畫圖 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 5 用函數封裝重複性指令-呼叫函數令烏龜畫正 n 邊形 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 6 畫多重旋轉圓,螺旋正方形 link

  • 從turtle海龜動畫 學習 Python - 7 遞歸 recursive - 高中彈性課程系列 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 8 碎形 (分形 fractal) link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 8.1 碎形 L-system link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 9 Python 物件導向介紹 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 9.1 Python 物件導向的練習 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 10 藝術畫 自定義海龜形狀 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 10.1 藝術畫 python繪製天然雪花結晶 https://blog.csdn.net/m0_47985483/article/details/122262036 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 10.2 藝術畫 Python 製作生成式藝術 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 11.1 氣泡排序 - 用 turtle 呈現演算法之執行動作 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 11.2 maze 迷宮 - 用 turtle 呈現演算法之執行動作 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 11.3 連分數演算法與轉轉相除法- 用 turtle 呈現演算法之執行動作 link

  • 從turtle海龜動畫 學習 Python - 高中彈性課程系列 11.4 最短路徑 Dijkstra- 用 turtle 呈現演算法之執行動作 link



5.5 用函數封裝重複性指令-呼叫函數令烏龜畫正 n 邊形

Ref: 官網的文件: python-3.3.2-docs-pdf-a4

正規的函數定義法:
An alternative is to just use the def statement and define a function in the usual way:

以下這個函數, 輸入 x,y 值, 會回應 x+y 的值

可以打開 IDLE 左上方 File/New File, 產生一個空白的類似小作家編輯器, 輸入以下程式碼, 再按 F5 執行編譯,

def adder(x, y):
return x + y

# Ref: 官網的文件: python-3.3.2-docs-pdf-a4

def adder(x, y):
    return x + y

再在 IDLE consola 畫面, 輸入 adder(2,3) 等指令,

>>> adder(2,3)
5

以下是一個會計算兩倍的函數, 隨意取一個名稱叫 foo(),

def foo(x):
    foo1=2*x
    return foo1

在再 IDLE consola 畫面輸入 foo(4) 等指令, 就會回 4 的倍數 8, 給你,
執行畫面

>>> 
===== RESTART: C:/Users/user/Desktop/test.py =====
>>> foo(4)
8
>>> foo(40)
80

EX: 解析以下官網的文件的第二個例子, 預測執行時會得出甚麼結果

def print_assign(name, value):
    return name +=+ str(value)

畫正5邊形用函數封裝

以下將上一節畫正五邊形的codes, 封裝為函數, 取名為 Pentagon( )
以下 codes 存成 草稿檔 (script file), 取名為 regularPentagon.py
輸入 codes 完之後, 按 F5執行編譯,
就會畫出正五邊形

import turtle

S=turtle.Turtle()

S.shape("turtle") # 形狀設成烏龜
S.turtlesize(3,3,4) #烏龜長寬放大3倍, 輪廓4%
#S.fillcolor("blue") # 烏龜身上內部的顏色
#S.pencolor("green") # 畫筆顏色
S.color('green',"blue")
S.pensize(10) #畫筆粗細
S.speed(2) # 烏龜移動速度 1->10, 0最快
S.penup() # 提起畫筆
S.goto(0,-100) # 跳躍至此座標
S.pendown() # 放下畫筆

def Pentagon(side):
    for i in range(5):
        S.forward(side)
        S.left(72)

Pentagon(200)

或是 按 F5執行之後, 再在 IDLE 輸入
>>>Pentagon(100)
就會畫出正五邊形
畫出正五邊形


畫正n邊形用函數封裝

進一步修改成畫出正 n 邊形之函數
先計算出正 n 邊形之內角, 再計算出其外角,
烏龜繪圖_正n邊形_內角計算
烏龜繪圖_正n邊形_內外角

根據以上計算出之正 n 邊形之外角, 2 π n \frac{2\pi}{n} n2π radian, 就可以直接修改上面畫正五邊形之函數, 改成為 畫正n邊形之函數, 暫時叫 regularPolygon(n, side),

如下

def regularPolygon(n, side):
    for i in range(n):
        T.forward(side)
        T.left(2*180/n)

再呼叫 regularPolygon(7, 200) 繪製正7邊形,
完整的 codes:

import turtle
S=turtle.Turtle()

S.shape("turtle") # 形狀設成烏龜
S.turtlesize(3,3,4) #烏龜長寬放大3倍, 輪廓4%
#S.fillcolor("blue") # 烏龜身上內部的顏色
#S.pencolor("green") # 畫筆顏色
S.color('green',"blue")
S.pensize(10) #畫筆粗細
S.speed(2) # 烏龜移動速度 1->10, 0最快
S.penup() # 提起畫筆
S.goto(0,-100) # 跳躍至此座標
S.pendown() # 放下畫筆


def regularPolygon(n, side):
    for i in range(n):
        S.forward(side)
        S.left(2*180/n)
# 繪製正7邊形
regularPolygon(7,200)

畫出正七邊形

用雙重(巢狀)迴圈畫多重正n邊形

如果我們想要畫出以下的效果
多重同邊正n邊形

我們可以進一步, 用雙重(巢狀)迴圈的概念, 呼叫上面定義好的畫正n邊形之函數, 形成雙重(巢狀)迴圈的概念,
定義一個函數 multiRegularPolygon(n, side), 對於輸入的 n, 畫出畫多重同邊正n邊形, 正3邊形到正 n 邊形.

def multiRegularPolygon(n, side):
    for i in range(3,n+1):
        regularPolygon(i, side)

完整的 codes, 從正三畫到正七邊形:

import turtle

S=turtle.Turtle()

S.shape("turtle") # 形狀設成烏龜
S.turtlesize(3,3,4) #烏龜長寬放大3倍, 輪廓4%
#S.fillcolor("blue") # 烏龜身上內部的顏色
#S.pencolor("green") # 畫筆顏色
S.color('green',"blue")
S.pensize(10) #畫筆粗細
S.speed(2) # 烏龜移動速度 1->10, 0最快
S.penup() # 提起畫筆
S.goto(0,-100) # 跳躍至此座標
S.pendown() # 放下畫筆

def regularPolygon(n, side):
    for i in range(n):
        S.forward(side)
        S.left(2*180/n)

def multiRegularPolygon(n, side):
    for i in range(3,n+1):
        regularPolygon(i, side)

multiRegularPolygon(7,200)

從正三畫到正七邊形

接著, 我們也可以直接用雙重迴圈的概念, 不使用上面定義好的畫正n邊形之函數,
直接畫多重同邊正n邊形,
定義一個函數, 對於輸入的 n, 畫出正3邊形到正 n 邊形

def multiRegularPolygon_double_for(n, side):
    for i in range(3,n+1):
        for k in range(i):
            T.forward(side)
            T.left(2*180/i)

輸入
>>>multiRegularPolygon_double_for(30, 40)
就會畫出正3邊形到正 29 邊形

以下草稿檔有三個函數:
1 畫出正 n 邊形之函數, regularPolygon(n, side)
2 用雙重迴圈的概念, 定義一個函數, 對於輸入的 n, 畫出正3邊形到正 n 邊形, multiRegularPolygon_double_for(n, side)
3 用呼叫正 n 邊形之函數, 定義一個函數, 對於輸入的 n, 畫出正3邊形到正 n 邊形,
multiRegularPolygon(n, side)

存成 script file, 取名為
multiRegularPolygon_double_for_loop.py
輸入完之後, 按 F5執行
會畫出正3邊形到正29邊形

import turtle
T = turtle.Turtle()
T.reset()
T.shape('turtle')
T.color('yellow','green')
turtle.bgcolor('black')
T.pensize(3)
T.penup()
T.goto(0,-100)
T.pendown()
#import math
def regularPolygon(n, side):
    for i in range(n):
        T.forward(side)
        T.left(2*180/n)

def multiRegularPolygon_double_for(n, side):
    for i in range(3,n+1):
        for k in range(i):
            T.forward(side)
            T.left(2*180/i)

    
def multiRegularPolygon(n, side):
    for i in range(3,n+1):
        regularPolygon(i, side)
        
multiRegularPolygon(29, 40)


  • 以下可以等進階時再細看
匿名函數

lambda function 的定義法
adder = lambda x, y: x+y
超過1行就用 def 的方法

print_assign = lambda name, value: name + ’=’ + str(value)

Q: 函數可以輸入函數為引數嗎? (有時稱為"高階函數", “泛函函數”)
Ans: 可以
先定義一個函數:
def test(f,n):
return f(n)

再輸入
>>> test(lambda x: x**2,3)
9

5.5.1 注意函數的局部變數 local variable 與全域變數 global variable 之互動狀況

函數的局部變數 local variable 與全域變數 global varibale, 與一般語言 C, Java 等類似, 只要注意至少有一點與 C 不同:

注意 Python 與 C 不同之處, function 內無法更改 外部的全域變數,
例如迷宮之例子, 全域變數 maze, success,
參考本系列博文: 從 Logo 海龜繪圖 學習 Python - 高中彈性課程系列 11 用 turtle 呈現演算法之執行動作, https://blog.csdn.net/m0_47985483/article/details/111172062 link

必須在 function 內, 再加一個 global maze, 才能更改 maze.

如果沒宣告, 會無法更改 全域變數 maze, success 之值, 會出現以下之 error:

>>> 
,,,,,
UnboundLocalError: local variable 'success' referenced before ass

20230310 練咨辰問 UnboundLocalError: local variable ‘a’ referenced before assignment

  • 外部變數 c=1, 在 fun 內 也有一個 c, c只能唯讀,
  • 如果在 fun 內要改外部變數 c, 要宣告 global 關鍵字
  • 如果在 fun 內更改變數 c, 沒宣告 global 關鍵字, 會直接視他為內部局部變數, 修改之值與外部c無關

以下跑一個小例子

# 20230310 練咨辰問 UnboundLocalError: local variable 'a' referenced before assignment
# 外部變數 c=1, 在 fun 內 也有一個 c, c只能唯讀,
# 如果在 fun 內要改外部變數 c=c+1, 要宣告 global 關鍵字
# 如果在 fun 內要更改變數 c, 沒宣告 global 關鍵字, 會直接視他為內部局部變數, 修改之值與外部c無關

c=1

# 外部變數 c=1, 在 fun 內只能唯讀
def readGolbalVariable():
    print("外部變數 c=1, 在 fun 內只能唯讀 ")
    print("global c read inner a function is ", c)

readGolbalVariable()

print()

# 如果在 fun 內更改變數 c, 沒宣告 global 關鍵字, 
# 會直接視他為內部局部變數, 修改之值與外部 c 無關
def localVariable():
    c=5
    c = c+1
    print("如果在 fun 內更改變數 c, 沒宣告 global 關鍵字,")
    print("會直接視他為內部局部變數, 修改之值與外部 c 無關,")
    print("c is local variable, c = 5, c=c+1 is ", c)

localVariable()

print()
# 外部之 c 仍然為 1
print("外部之 c 仍然為 1,")
print("global c read outer a function is still", c)


print()
# 如果在 fun 內要改外部變數 c=c+1, 要宣告 global 關鍵字
def globalVariableClaim():
    global c
    c = c+1
    print('如果在 fun 內要改外部變數 c=c+1, 要宣告 global 關鍵字')
    print("c is claimed as a global variable, c is 1, c=c+1 is ",c)

globalVariableClaim()

print()

# 外部之 c 已被改變
print('外部之 c 已被改變')
print("global c read outer a function is now changed to be", c)

##>>> 
##================= RESTART: C:/Users/user/Desktop/test_local.py =================
##外部變數 c=1, 在 fun 內只能唯讀 
##global c read inner a function is  1
##
##如果在 fun 內更改變數 c, 沒宣告 global 關鍵字,
##會直接視他為內部局部變數, 修改之值與外部 c 無關,
##c is local variable, c = 5, c=c+1 is  6
##
##外部之 c 仍然為 1,
##global c read outer a function is still 1
##
##如果在 fun 內要改外部變數 c=c+1, 要宣告 global 關鍵字
##c is claimed as a global variable, c is 1, c=c+1 is  2
##
##外部之 c 已被改變
##global c read outer a function is now changed to be 2

簡而言之: 如果內部與外部有同名之變數,

  • 內部同名變數沒有賦值, 只有讀取他的值, 此時會視他為與外部變數同一個, 取用外部變數的值,
  • 如果內部同名變數有賦值, 或做更改值的動作, 此時會視他為內部變數(屏蔽掉外部變數), 此時對他做的動作與, 外部同名變數無關.

Ref: 從turtle海龜動畫學習Python-高中彈性課程1 http://t.csdn.cn/HmXlq link

  • 以上可以等進階時再細看

5.6 旋轉正多邊形_左下頂點為中心: 封裝為函數, 輸入引數: n 邊, m 重, side 邊長, 就會畫正 n 邊形左下頂點為中心 m 重旋轉之圖形

在这里插入图片描述

程式碼:

import turtle
T = turtle.Turtle()
T.clear()
T.home()
T.shape('turtle')
T.color('yellow','green')
turtle.bgcolor('black')
T.pensize(3)
T.penup()
#T.goto(0,-100)
T.pendown()
#import math
def regularPolygon(n, side):
    for i in range(n):
        T.forward(side)
        T.left(2*180/n)

    
def center_A_multiSameRegularPolygon(n, m, side):
    for i in range(1,m+1):
        regularPolygon(n, side)
        T.lt(360/m)

>>> center_A_multiSameRegularPolygon(6, 8, 50)
在这里插入图片描述

5.7 旋轉正多邊形_左下頂點為中心 之型態實驗

參考以下網站, , Dr. Kubeš - Galileo School 網址, 上課講義 DrawingGeometricShapes.pdf, 用 Scratch 畫旋轉正多邊形的各種圖案
Ref: https://sites.google.com/site/matejkubesgalileoschool/computer-science/ict-7ab-8a-scratch/learning-to-program-with-scratch/drawing-geometric-shapes
link

5.7.1 旋轉正3邊形

以下旋轉正3邊形
PatternByRotateTriangle
旋轉正3邊形, 5重, 邊長100
>>>center_A_multiSameRegularPolygon(3, 5, 100)
center_A_multiSameRegularPolygon(3, 5, 100)

5.7.2 旋轉正4邊形

以下為旋轉正4邊形
PatternByRotateSquare
旋轉正4邊形, 30重, 邊長100
>>>center_A_multiSameRegularPolygon(4, 30, 100)
center_A_multiSameRegularPolygon(4, 30, 100)

5.7.3 旋轉正5邊形

以下為旋轉正5邊形
PatternByRotatePentagon
旋轉正5邊形, 12重, 邊長100
>>>center_A_multiSameRegularPolygon(5, 12, 100)
在这里插入图片描述

5.7.4 旋轉正6邊形

以下為旋轉正6邊形
PatternByRotateHexagon
旋轉正6邊形, 12重, 邊長100
>>>center_A_multiSameRegularPolygon(6, 12, 100)
center_A_multiSameRegularPolygon(6, 12, 100)

5.7.5 旋轉正7邊形

以下為旋轉正7邊形
PatternByRotateHeptagon
旋轉正7邊形, 15重, 邊長100
>>>center_A_multiSameRegularPolygon(7, 15, 100)
center_A_multiSameRegularPolygon(7, 15, 100)

5.7.6 旋轉正8邊形

以下為旋轉正8邊形
PatternByRotateOctagon
旋轉正8邊形, 12重, 邊長100
>>>center_A_multiSameRegularPolygon(8, 12, 100)
center_A_multiSameRegularPolygon(8, 12, 100)_頂點重合

5.7.7 旋轉正9邊形

以下為旋轉正9邊形
PatternByRotateDecagon
旋轉正9邊形, 9重, 邊長100
>>>center_A_multiSameRegularPolygon(9, 9, 100)
旋轉正9邊形, 9重, 邊長100

旋轉正9邊形, 27重, 邊長100
>>>center_A_multiSameRegularPolygon(9, 27, 100)

center_A_multiSameRegularPolygon(9, 27, 100)_頂點無重合

Ref:

  1. https://docs.python.org/zh-tw/3/library/turtle.html#turtle.shape link

  2. https://docs.python.org/3/library/turtle.html#turtle.shape link

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值