Processing math: 100%
< Back

Lab 6: Creating Functions

As usual, create a directory to hold today's files. All programs that you write today should be stored in this directory.

$ cd ~/cs120/labs
$ mkdir lab6
$ cd lab6


Rectangle Function

Functions are great for code reuse. A well written function can be used in many different programs.

Details

In Emacs, create a Python program in a file called rectangle.py. Your program should use the turtle module to draw several rectangles on the turtle window.

Your program should define the function draw_rectangle(x, y, width, height). The parameters x and y specify the location to draw the rectangle on the screen. The width parameter specifies the size of the rectangle in the x direction, and the height parameter specifies the size of the rectangle in the y direction.

The rectangle should be drawn centered on the coordinate specified by the x and y parameters. Make sure you use proper variable names following the course's code conventions.

Example

>>> rectangle.draw_rectangle(x=0, y=0, width=10, height=25)
>>> rectangle.draw_rectangle(x=10, y=15, width=15, height=5)
Turtle Graphics Star

Hint

Challenge

Write a function to draw an octagon. The function should have parameters to specify the location and size of the octagon to draw. Use it to draw several octagons on the turtle screen.

Turtle Graphics Pentagram

Houses

A benefit of writing functions is that we can use them to simplify complex programs. For example, you now have a function written to draw a square. You can use that function to create another function that draws something with multiple squares. And you can use that function to create even more complex drawings.

Details

In Emacs, create a Python program in a file called house.py. Your program should use the turtle module to draw a house in the turtle window.

You need at least two new functions: draw_triangle(x, y, side_length) and draw_house(x, y). Both of these functions should have parameters to make drawing with these functions easier.

Your drawings should always be drawn centered on the specified coordinates. Make sure your house is drawn at the correct location on the turtle window as seen below. Make sure you use proper variable names following the course's code conventions.

Example

>>> house.draw_house(-100, 0)
>>> house.draw_house(100, 0)
Turtle Graphics Star

Hint

Challenge

Your drawing probably looks pretty bland as of right now. However, you can easily add color to your drawings using the turtle module. Add color to at least the door and roof of the house, and add a green rectangle to the scene to represent grass.