Draw polygon in polygons (regular polygons)

Question:

This is my code that draws regular polygons:

import turtle

tr = turtle.Turtle()

tr.lt(150)
for x in range(3,13):
    for i in range(x):
        tr.fd(80)
        tr.lt(360//x)

turtle.done()

This is my output:
actual output

But my expected output is:
expected output

Can you help me?

Asked By: Roham

||

Answers:

As already pointed in the comments

You probably want to move the turtle at thee end of the polygon, so the ends won’t be connected

  • @mousetail

Looks like you need to calculate the radius offset and move in/out from the center if you want them all concentric. Currently you’re always starting the first/last vertex at the same point.

  • @CrazyChunky

After having a quick look in the turtle methods

I came up with this

import turtle
import math
tr = turtle.Turtle()

r0 = 20
tr.lt(150)
for x in range(3,13):
    points = [
        (r0 * (x-1) * math.cos(k*2*math.pi/x),
         r0 * (x-1) * math.sin(k*2*math.pi/x))
        for k in range(1,x+1)
    ]
    tr.penup() # avoid creating a line connecting two polygons
    tr.goto(*points[-1])
    tr.pendown() # draw one polygon
    for tx, ty in points:
        tr.goto(tx,ty);
turtle.done()

PS.: I have never heard about this module before, and it was a surprise to see that it was installed in my machine.

Answered By: Bob

A simple-minded solution using circle() to do our work for us:

import turtle
from math import pi

for sides in range(3, 13):
    radius = 40 * sides / pi

    turtle.penup()
    turtle.sety(-radius)
    turtle.pendown()

    turtle.circle(radius, steps=sides)

turtle.hideturtle()
turtle.done()

enter image description here

Answered By: cdlane