kile
kile

Reputation: 141

Turtle can't go back to the original point after several loops

Here is the code. I have tried the following.

enter image description here Why does this happen? Can anyone explain?

import turtle


turtle.penup()
turtle.setposition(0,300)
turtle.pendown()

turtle.pencolor("red")

turtle.speed(10)

for i in range(6 , 15, 2):

    step = int(360 / i)

    turtle.setheading(int(90 - (180 - step)/2))
    

    for j in range(1, 1 + i):

        turtle.right(step)

        turtle.forward(10*i)
        
turtle.exitonclick()

Is this because of floating number in calculation?

Upvotes: 0

Views: 51

Answers (1)

Ross MacArthur
Ross MacArthur

Reputation: 5449

Yes this is because 360 is not nicely divisible by 14. Which is the last iteration of the outer loop.

  • i = 6: step is 360 / 6 => 60
  • i = 8: step is 360 / 8 => 45
  • i = 10: step is 360 / 10 => 36
  • i = 12: step is 360 / 12 => 30
  • i = 14: step is 360 / 14 => 25.714285714

If you change your code to not truncate the step value from a float to an integer then it works fine:

for i in range(6, 15, 2):
    step = 360.0 / i
    turtle.setheading(90 - (180 - step)/2)

    for j in range(1, i + 1):
        turtle.right(step)
        turtle.forward(10*i)

Upvotes: 4

Related Questions