How to Draw an n-sided Polygon in Python Using the Turtle Library

# import turtle library
import turtle
# get screen
Window = turtle.Screen()
# name turtle
bob = turtle.Turtle()

# prompt user for num of sides they want their polygon to be
sidesInput = int(input("Enter a number greater than or equal to 3: "))  

# if the user inputed a number less than 3 for the number of sides they want in their polygon, print ERROR because a polygon cannot have less than 3 sides
if sidesInput < 3 :
    print('ERROR')

# initialize variables    
i = 0
forward = ''
left = ''

# using a while-loop
while i in range (sidesInput):
# make forward variable equal to 100
    forward = 100
# make left variable 360 degrees divided by the number of sides inputed by user to get the angle at which to rotate to make the figure
    left = 360/sidesInput
# while condition- make i = i + 1 
    i += 1
  
# turtle 
# make bob go forward by forward variable 
    bob.forward(forward)
# make bob go left by left variable 
    bob.left(left)

Looping Examples-Graphics with the Turtle Library

# Example #1:
# import the turtle method
import turtle
# get the Screen
window = turtle.Screen
# initialize Turtle Variable
bob = turtle.Turtle()
# Make speed fast (0 is the fastest)
bob.speed(0)
# for loop
# start = 0, stop = 250, iteration = 1 (you don't have to put this because if no iteration is typed in the range, it assumes the iteration is 1.
for i in range(0,250):
	# move bob forward and iterate by 1 to make bob loop
	bob.forward(i+1)
        # we are trying to make the base hexogonal and iterate it
        # we use bob.left(60) to turn bob 60 degrees (the angle of each 
        side of a hexagon)
	bob.left(60)

Output:

# Example #2:
# import Turtle Method
import turtle
# get Screen
window = turtle.Screen
# Initialize Turtle (I named mine 'bob')
bob = turtle.Turtle()
# make speed fast (zero = fastest)
bob.speed(0)
# for-loop
# start = 0, end = 500, iteration = 1
for i in range(0,500):
	# move bob forward and iterate by 1
	bob.forward(i+1)
        # move bob left by 65 degrees (always go a couple of degrees off from the angle of a side of a hexagon if you want to create the hexagonal spiral like shape
	bob.left(65)

Output:

Design a site like this with WordPress.com
Get started