How to draw pentagon, hexagon and other polygons in Python Turtle?

Polygon is a n-sided closed figure. All the sides of a polygon are of equal length. The naming of a polygon depends on how many sides it is having. An exterior angle of a polygon is 360/(number of sides). So, for a pentagon, it will be 72. For a hexagon, it will be 60. And so on.

Number of Sides Polygon name Exterior Angle
5 Pentagon 72
6 Hexagon 60
7 Heptagon 51.42
8 Octagon 45
9 Nanogon 40
10 Decagon 36

In order to draw pentagon, hexagon and other polygons, we will use the above-mentioned properties.

Draw Pentagon in Python Turtle

#Python programming to draw pentagon in turtle programming
import turtle

t = turtle.Turtle()
for i in range(5):
   t.forward(100) #Assuming the side of a pentagon is 100 units
   t.right(72) #Turning the turtle by 72 degree

Output of the above program

Pentagon in Python Turtle

Explanation of the above code-

for i in range(5):
   t.forward(100)
   t.right(72)

We are assuming the side of a pentagon is 100 units. So, we will move the turtle in the forward direction by 100 units. And then turn it in the clockwise direction by 72°. Because the exterior angle of a pentagon is 72° These two statements are repeated 5 times to obtain Pentagon.

Draw Hexagon in Python Turtle

#Python programming to draw hexagon in turtle programming
import turtle

t = turtle.Turtle()
for i in range(6):
   t.forward(100) #Assuming the side of a hexagon is 100 units
   t.right(60) #Turning the turtle by 60 degree

Output of the above program

Hexagon in Python Turtle

Draw Heptagon in Python Turtle

#Python programming to draw heptagon in turtle programming
import turtle

t = turtle.Turtle()
for i in range(7):
   t.forward(100) #Assuming the side of a heptagon is 100 units
   t.right(51.42) #Turning the turtle by 51.42 degree

Output of the above program

Heptagon in Python Turtle

Draw Octagon in Python Turtle

#Python programming to draw octagon in turtle programming
import turtle

t = turtle.Turtle()
for i in range(8):
   t.forward(100) #Assuming the side of a octagon is 100 units
   t.right(45) #Turning the turtle by 45 degree

Output of the above program

Octagon in Python Turtle

Draw polygon in Python Turtle

#Python programming to draw polygon in turtle programming
import turtle

t = turtle.Turtle()
numberOfSides = int(input('Enter the number of sides of a polygon: '))
lengthOfSide = int(input('Enter the length of a side of a polygon: '))
exteriorAngle = 360/numberOfSides
for i in range(numberOfSides):
   t.forward(lengthOfSide)
   t.right(exteriorAngle)

Output of the above program

User Input in Python Turtle Polygon in Python Turtle

Recommended Posts