Alyssa Kelley
Alyssa Kelley

Reputation: 47

How to draw Circle using Turtle in Python 3

This is the code that I have already, but it is saying I need to define 'polygon' which I know I need to, but not exactly sure how and different ways that I have been trying just keeps giving me errors.

import turtle
import math

apple=turtle.Turtle()

def draw_circle(t, r):
    circumference = 2 * math.pi * r
    n = 50
    length = circumference / n
    polygon(t, n, length)

draw_circle(apple, 15)

turtle.exitonclick()

Upvotes: 1

Views: 19070

Answers (3)

msbodw001
msbodw001

Reputation: 318

If you really need to define a polygon.

from turtle import *
import math

apple = Turtle()

def polygon(t, n, length):
    for i in range(n):
        left(360/n)
        forward(length)

def draw_circle(t, r):
    circumference = 2 * math.pi * r
    n = 50
    length = circumference / n
    polygon(t, n, length)
    exitonclick()

draw_circle(apple, 30)

Upvotes: 1

BlooB
BlooB

Reputation: 965

here is a function for polygon:

def drawPolygon (ttl, x, y, num_side, radius):
  sideLen = 2 * radius * math.sin (math.pi / num_side)
  angle = 360 / num_side
  ttl.penup()
  ttl.goto (x, y)
  ttl.pendown()
  for iter in range (num_side):
    ttl.forward (sideLen)
    ttl.left (angle)

Here is how you use it:

def main():
  # put label on top of page
  turtle.title ('Figures')

  # setup screen size
  turtle.setup (800, 800, 0, 0)

  # create a turtle object
  ttl = turtle.Turtle()

  # draw equilateral triangle
  ttl.color ('blue')
  drawPolygon (ttl, -200, 0, 3, 50)

  # draw square
  ttl.color ('red')
  drawPolygon (ttl, -50, 0, 4, 50)

  # draw pentagon
  ttl.color ('forest green')
  drawPolygon (ttl, 100, 0, 5, 50)

  # draw octagon
  ttl.color ('DarkOrchid4')
  drawPolygon (ttl, 250, 0, 8, 50)

  # persist drawing
  turtle.done()

main()

Dont Forget to add import turtle, math

Upvotes: 1

uphill
uphill

Reputation: 409

use the circle method

import turtle
import math

apple=turtle.Turtle()

def draw_circle(t, r):
    turtle.circle(r)

draw_circle(apple, 15)

turtle.exitonclick()

Upvotes: 4

Related Questions