解释锻炼代码Python乌龟螺旋

时间:2018-08-26 14:39:10

标签: python turtle-graphics spiral

我是编程的初学者,尝试通过Python在线课程进行一些简单的练习。我找到了解决方案,但我听不懂代码。您能在下面的一些评论中解释我吗? (我会很感激。)

import turtle from math 
import sin,cos,pi 

t=turtle.Turtle() 
t.speed(0)

n=50  
d=10  
r=0 
x,y = 0, 0 
cur_r = r

for i in range(n): 
    for a in range(1,360, 4): 
        r = cur_r + d*a/360.0 
        a *= pi/180.0 y = r*sin(a) 
        x = r*cos(a) 
        turtle.goto(x,y) 
        cur_r += d

1 个答案:

答案 0 :(得分:0)

首先,让我们将其从不可行的代码片段转换为可运行的程序:

import turtle
from math import *

n = 1
d = 2
cur_r = 3

for i in range(n):
    for a in range(1, 360, 4):
        r = cur_r + d * a / 360.0
        a *= pi / 180.0
        x, y = r * cos(a), r * sin(a)
        turtle.goto(x, y)
        cur_r += d

turtle.mainloop()

现在让我们尽可能地解释一下。首次进口:

import turtle  # turtle graphics for plotting

from math import *  # get trig routines sine and cosine plus pi constant

下一个全局变量:

n = 1  # number of revolutions around the spiral

d = 2  # growth factor (delta) for spiral radius (in 4 degrees steps)

cur_r = 3  # initial setting of current spiral radius

代码:

for i in range(n):  # for each revolution of the spiral

    for a in range(1, 360, 4):  # angle from 1 to 359 in 4 degree steps

        r = cur_r + d * a / 360.0  # new radius based on current one + delta

        a *= pi / 180.0  # convert angle from degrees to radians

        x, y = r * cos(a), r * sin(a)  # get cartesian coordinates from polar

        turtle.goto(x, y)  # draw a line from previous point to this one

        cur_r += d  # add delta to current radius before repeating process

turtle.mainloop()  # turn control over to tkinter's event handler

错误:

for a in range(1, 360, 4):

可能应该是:

for a in range(0, 360, 4):

和'4'应该是一个附加变量,不是硬编码的。由于我们已经从数学库中导入了所有内容:

a *= pi / 180.0

可以写成:

a = radians(a)

目前尚不清楚此行的作用:

r = cur_r + d * a / 360.0

不仅完成以下任务:

r = cur_r

d * a / 360.0的范围仅从d/360到'd'。修改后的代码:

import turtle
from math import cos, sin, radians

revolutions = 1
delta = 2
radius = 3
steps = 4

for i in range(revolutions):
    for angle in range(0, 360, steps):
        angle = radians(angle)
        x, y = radius * cos(angle), radius * sin(angle)
        turtle.goto(x, y)
        radius += delta

turtle.mainloop()