0

How to draw octagon inside an octagon where both centered in same point in turtle using Python? This what I did so far:

import turtle

for i in range(8):
    turtle.forward(100)
    turtle.right(360/8)

    turtle.pendown()

    turtle.goto(20, -20)


    turtle.penup()


    for i in range(8):
           turtle.forward(40)
           turtle.right(360/8)
unor
  • 92,415
  • 26
  • 211
  • 360
Salech Alhasov
  • 145
  • 1
  • 8

3 Answers3

1

just put the pen down, trace the first pentagon in the first for loop, travel half the distance of the first line and begin your new smaller octagon there

import turtle

turtle.pendown()
for i in range(8):
    turtle.forward(100)
    turtle.right(360/8)

turtle.forward(50)
for i in range(8):
       turtle.forward(FIGURE OUT WHAT THE NEW DISTANCE IS)
       turtle.right(360/8)

if it was important to jump to point 20,-20 and start with octagon 40 length there this would be the version

import turtle

turtle.pendown()
for i in range(8):
    turtle.forward(100)
    turtle.right(360/8)

turtle.penup()
turtle.goto(20, -20)
turtle.pendown()

for i in range(8):
       turtle.forward(40)
       turtle.right(360/8)
user2255757
  • 756
  • 1
  • 6
  • 24
1

Remember that points on a circle are given by the formula

x = r * cos(theta)
y = r * sin(theta)

where r is the radius and theta is the angle subtended by the ray extending from the origin to the point and the x-axis. The vertices of an octagon are equally spaced on a circle. So if we choose equally spaced thetas from 0 to 2 pi radians, then we'll have the vertices of an octagon:

import turtle
from math import pi, cos, sin

def ngon(n, dist, phase, shift=(0,0)):
    theta = 2 * pi / n
    x0, y0 = shift
    turtle.penup()
    x = dist * cos(phase) + x0
    y = dist * sin(phase) + y0
    turtle.goto(x, y)
    turtle.pendown()
    for i in range(1, n+1):
        x = dist * cos(i*theta + phase) + x0
        y = dist * sin(i*theta + phase) + y0
        turtle.goto(x, y)

def demo_ngon():
    turtle.speed(0.1)
    turtle.width(2.0)
    ngon(8, dist=100, phase=0)
    ngon(8, dist=68, phase=0)
    turtle.mainloop()

demo_ngon()
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
-1
import turtle

for i in range(8):
    turtle.forward(100)
    turtle.right(360/8)

turtle.forward(50)
for i in range(8):
       turtle.forward(40)
       turtle.right(360/8)
Patrick W
  • 1,485
  • 4
  • 19
  • 27