学习了嵩天老师的课程里的科赫曲线雪花画法,想自己再加工一下变成线条颜色渐变的雪花,于是引入turtle.color,并定义r,g,b作为颜色赋值,在函数中将r,g,b设为global变量
import turtle
def koch(size,n,r,g,b):
global r,g,b
turtle.colormode(255)
turtle.color(r,g,b)
if n ==0:
turtle.fd(size)
else:
for angel in [0,60,-120,60]:
turtle.left(angel)
koch(size / 3, n - 1,r,g,b)
r = (r+1)%200
g = (g + 1)%200
b = (b +1 )%200
if __name__ == '__main__':
turtle.setup(600,600)
turtle.penup()
turtle.goto(-200,100)
turtle.pendown()
turtle.pensize(2)
level=4
r,g,b= (218, 112, 214)
koch(400,level,r,g,b)
turtle.right(120)
koch(400, level,r,g,b)
turtle.right(120)
koch(400, level,r,g,b)
turtle.hideturtle()
运行报错SyntaxError: name ‘r’ is parameter and global
原来是因为变量不能同时作为global变量和函数之间传递的变量。
修