""" 作者: 功能:draw five_pointed star 版本:3.0 日期:2019/3/16 新增功能:使用迭代操作繪製重複不同大小的圖形 """ import turtle # def draw_pentagram(size): # """ # draw five_pointed star function # """ # count = 1 # while count <= 5: # turtle.forward(size) # turtle.right(144) # count += 1 while(size <= 100) def draw_recursive_pentagram(size): """ 迭代繪製五角星 """ count = 1 while count <= 5: turtle.forward(size) turtle.right(144) count += 1 #五角星繪完成,更新參數 size += 50 draw_recursive_pentagram(size) def main(): turtle.penup() turtle.backward(200) turtle.pendown() turtle.pensize(2) turtle.pencolor('red') size = 50 draw_recursive_pentagram(200) turtle.exitonclick() if __name__== '__main__': main()
遞歸:
- 函數定義中調用函數自身的方式叫遞歸
- 能非常簡潔地解決重要問題
- 每次函數調用時,函數參數會臨時存儲,相互沒有影響
- 達到終止條件時,各函層結束運算,返回計算結果
- 要注意終止條件的構建,否則遞歸無法正常返回結果