递归函数:
"""
功能:五角星的绘制
"""
import turtle
def draw_pentagram(size):
"""
绘制五角星(使得结构简洁,程序化)
"""
# 绘制一个
count = 1
while count <= 5:
turtle.forward(size)
turtle.right(144)
# count = count + 1
count+=1
# 迭代绘制五角星
def draw_recuisive_pentagram(size):
count = 1
while count <= 5:
turtle.forward(size)
turtle.right(144)
# count = count + 1
count += 1
# 五角星绘制完成,更新参数
size+=10
if size<=100:
draw_recuisive_pentagram(size)
draw_recuisive_pentagram(size)
def main():
"""
主函数
"""
turtle.penup()
turtle.backward(200)
turtle.pendown()
turtle.pensize(2)
turtle.pencolor("red")
# 计数器
size=50
draw_recuisive_pentagram(size)
# while size<=500:
# # 调用函数
# draw_pentagram(size)
# # size=size+50
# size+=50
turtle.exitonclick()
if __name__=='__main__':
main()
分形树绘制:
"""
利用递归函数绘制分形树
"""
import turtle
def draw_branch(branch_length):
"""
绘制分形树
"""
if branch_length>5:
# 绘制右侧树枝
# 主干
turtle.forward(branch_length)
print("向前",branch_length)
# 向右转20度
turtle.right(20)
print("向右转20度")
draw_branch(branch_length-15)
# 绘制左侧树枝
turtle.left(40)
draw_branch(branch_length-15)
# 返回之前的树枝
turtle.right(20)
turtle.backward(branch_length)
print("向后", branch_length)
def main():
"""
主函数\
"""
turtle.left(90)
# 坐标轴的方向是向右的,所以进行转角度
# 因为绘制的话是从画布的中心点开始,所以若初始值比较大的话会看不到,所以移动绘制的位置
# 抬起画笔
turtle.penup()
turtle.backward(150)
# 放下画笔
turtle.pendown()
# 加颜色
turtle.color("brown")
draw_branch(100)
# 实参
turtle.exitonclick()
if __name__ == '__main__':
main()
实现效果:
习题: