Search code examples
pythonpython-turtle

How to draw a circle using turtle in python?


I wanted ask how can I draw a circle using turtle module in python just using turtle.forward and turtle.left? I use the code below:

 for i in range(30):
     turtle.forward(i)
     turtle.left(i)  
 turtle.done()

What I get is that the line does not stop once I get the full cirle. How can I code so that I have a circle of specific radius and that I have a full stop once the circle is drawn (without using turtle.circle).


Solution

  • I made this image as a reference, enter image description here

    Essentially you need to draw the inscribed polygon with n sides.

    The initial left turn will be ϴ/2.

    Then forward by a = 2rsin(ϴ/2).

    Each forward is followed by a left turn of the full ϴ, except that after the last forward we want only a left turn of ϴ/2 so that the heading will be correctly updated to be tangential to the circle (or arc).

    Something like this,

    import turtle
    import math
    
    def circle2(radius,extent=360,steps=360):
        if extent<360 and steps==360:
            steps=extent
        
        theta=extent/steps
        step_size=2*radius*math.sin(math.radians(theta/2))
        turtle.left(theta/2)
        turtle.forward(step_size)
        for i in range(1,steps):
            turtle.left(theta)
            turtle.forward(step_size)
        
        turtle.left(theta/2)
        
    
    turtle.hideturtle()
    turtle.speed(0)
    turtle.getscreen().tracer(False)
    
    circle2(50)
    circle2(100,180)
    turtle.up()
    turtle.home()
    turtle.down()
    circle2(130)
    circle2(130,360,10)
    
    turtle.update()
    turtle.mainloop()
    

    enter image description here