Study Guide

2.3.5 Rectangle CodeHS Answers

2.3.5 Rectangle CodeHS Answers

The most common answer is:

forward(50)
left(90)
forward(100)
left(90)
forward(50)
left(90)
forward(100)
left(90)

This code snippet is a straightforward procedure to draw a rectangle using turtle graphics in Python. This specific rectangle has a width of 50 units and a height of 100 units. We can encapsulate the code in a function to make it more reusable and organized.

Additionally, we’ll include the necessary import and setup to make it a complete, runnable program:

import turtle

def draw_rectangle():
    # Draw a rectangle with a width of 50 units and a height of 100 units
    for _ in range(2):
        turtle.forward(50)  # Width
        turtle.left(90)
        turtle.forward(100)  # Height
        turtle.left(90)

# Setup turtle environment
turtle.speed(1)  # Set drawing speed to moderate

draw_rectangle()  # Call the function to draw the rectangle

turtle.done()  # Keep the window open until it's manually closed

This code uses a loop to simplify the repetition in drawing the rectangle’s sides. The loop iterates twice, each time drawing a short side (50 units) followed by a long side (100 units) of the rectangle. By using a function, you can easily draw a rectangle anywhere in your turtle graphics program by calling draw_rectangle().

To draw rectangles of different sizes, you could modify the function to accept parameters for width and height, making it more versatile.