Today are main goals are: 1. Writing functions; 2. Start using some more advanced graphics functions that someone else has made for us!

Functions

Functions are just encapsulations of programs we know how to write and want to repeatedly use. For instance, if we had our turtle fred in the before times we’d have them draw a square by:

forward(fred, 100)
right_turn(fred, 90)
forward(fred, 100)
right_turn(fred, 90)
forward(fred, 100)
right_turn(fred, 90)
forward(fred, 100)
right_turn(fred, 90)

But wouldn’t it be more convenient to be able to tell fred “please draw a square?” That’s what functions are for! We can take what we have above and encapsulate it into a function. We just need to know the syntax or recipe necessary.

# function header
def draw_square():
    # function body
    forward(fred, 100)
    right_turn(fred, 90)
    forward(fred, 100)
    right_turn(fred, 90)
    forward(fred, 100)
    right_turn(fred, 90)
    forward(fred, 100)
    right_turn(fred, 90)

# now we call our new function!
draw_square()

Now, if we want fred to draw a square, we just call the draw_square() function!

But this function would only allow fred to draw one kind of square: one with side length of 100. So we could add a parameter or input to the function which gives us access to a variable inside the function’s body:


def draw_square(side_length):
    # Parameters are initialized by like regular variables
    #   with whatever value the function is called with
    #   side_length = 100
    forward(fred, side_length)
    right_turn(fred, 90)
    forward(fred, side_length)
    right_turn(fred, 90)
    forward(fred, side_length)
    right_turn(fred, 90)
    forward(fred, side_length)
    right_turn(fred, 90)

draw_square(100)

And now fred can draw squares with sides of ANY length!


Graphics

There are two functions that we learn about oval and rectangle which we practice using…but then also use to define our own new fun functions! This is exactly what we do in the tutorial and homework this week so try to follow along as we design each function. If you get stuck or are confused on a certain part, bring those questions to the tutorial! Feel free to watch the videos at super-speed or pause depending on your working style.

Note: Please please please watch the videos before attempting the tutorial or homework exercise. It demonstrates exactly the same logic you’ll need in order to complete those assignments.


Today's Resources

1. Exercise Files

Download Exercise Files

2. Slides

3. Pre-Recorded Lecture Video(s), Mini-Quizzes, and Live Recordings

Available Videos
Link Title Type Duration
Video 1 Introduction pre-recorded 3:10
Video 2 Ovals pre-recorded 16:05
Video 3 Rectangles

(MQ - No Longer Available)

video_quiz 10:32

4. Supplemental Materials

  • Charles Severance - Ch 4: Functions – Python for Everybody (ReadingVideo)