INST326 Homework 02 Framework

Debug the Following

The following code should allow a user to specify the number of sides of a polygon, and the code should draw a polygon of the appropriate construction on the turtle screen. Unfortunately, there are several errors in this code.

Assignment

  1. Correct the syntax errors in the code, so it runs.
  2. Correct the runtime errors in the code, so it gracefully handles corner cases (polygons of small sides mean what?)
  3. Correct the semantic errors in the code, so it produces correct output.

Turtle Setup and Configuration

In [ ]:
# Import the turtle package for drawing
import turtle
In [ ]:
# Create a screen on which we draw
screen = turtle.Screen()

# Configure a default size
dimX = 400
dimY = 400
screen.setup(dimX, dimY)

Accept User Input

In [ ]:
numSides = int(input("How many sides do you want in your polygon? "))
In [ ]:
print("Sides you requested:", numSides)

Fix the following code

In [ ]:
# Reset the screen (this code is good)
turtle.clearscreen()
screen.reset()
screen.screensize(dimX, dimY)
ttl = turtle.Turtle()
ttl.penup()
ttl.setposition(0, -150)
ttl.pendown()
ttl.speed(9) # Make tracing fast

# Constant side length
sideLength = 100

## CORRECT THE CODE BELOW

if ( sideLength > -1 ):
    interiorAngle = (numSides - 2) * 180 / numSides
    print("Each angle:", interiorAngle)

    for i in range(0, numSides):
        ttl.forward(sideLength)
        ttl.left(180-interiorAngle)
else:
    print("Invalid number of sides")
In [ ]:
turtle.done()
In [ ]: