Home > Blockchain >  How do I create any regular polygon using turtle?
How do I create any regular polygon using turtle?

Time:12-01

So I have an assignment that asked me to draw any regular polygon using Turtle and I created the code. It works but my mentor said to try again. I would like to know what I did wrong, Thank you!

The requirements for this assignment are:

  • The program should take in input from the user.
  • The program should have a function that:
    • takes in the number of sides as a parameter.
    • calculates the angle
    • uses the appropriate angle to draw the polygon
from turtle import Turtle

turtle = Turtle()
  
side = int(input("Enter the number of the sides: "))
    
def poly():
    for i in range(side):
        turtle.forward(100)
        turtle.right(360 / side)
        
        
poly()

CodePudding user response:

I think this might be better suited on math stackexchange.

A regular polygon has interior angles (n−2) × 180 / n. Theres a good blog post on that here.

You just need to change the angle by which you rotate every time:

from turtle import Turtle

turtle = Turtle()
  
num_sides = int(input("Enter the number of the sides: "))
    
def poly():
    for i in range(num_sides):
        turtle.forward(100)
        # change this bit
        turtle.right((num_sides - 2) * 180 / num_sides)
        
        
poly()

CodePudding user response:

This is the function I used to draw a polygon using Turtle:

Draws an n-sided polygon of a given length. t is a turtle.

def polygon(t, n, length):
angle = 360.0 / n
polyline(t, n, length, angle)
  • Related