← Python functions and events

Functions

Give a group of commands a name, then use that name again and again.

Every app is built from small named functions that other code calls. You are about to write your first.

You already know how to repeat steps with a loop. Now you will give a whole shape a name.

PredictRead the code and say what it will do before you run anything. A wrong guess is fine: it shows you what to look for.

Predict

functions.py
from turtle import *

for i in range(4):
    forward(100)
    right(90)

penup()
forward(150)
pendown()

for i in range(4):
    forward(100)
    right(90)

penup()
forward(150)
pendown()

for i in range(4):
    forward(100)
    right(90)

This program draws three squares by repeating the same code. What does it draw? Count how many times the number 100 appears.

RunRun it and compare the result with your prediction.

Run

Run it. Then make all three squares half as big. Notice how many places you had to change.

functions.py
from turtle import *

for i in range(4):
    forward(100)
    right(90)

penup()
forward(150)
pendown()

for i in range(4):
    forward(100)
    right(90)

penup()
forward(150)
pendown()

for i in range(4):
    forward(100)
    right(90)
Try it yourselfYour edits are saved in this browser.

InvestigateTrace how each line of code connects to what you see.

Investigate

def square(): gives the loop a name. The steps only run when the name is called: square().

functions.py
from turtle import *


def square():
    for i in range(4):
        forward(100)
        right(90)


square()
penup()
forward(150)
pendown()
square()
penup()
forward(150)
pendown()
square()

Compare this with the copy-and-paste version from the last step.

What does each part of this program do?

Build the function from scrambled lines.

This is one file.

from turtle import *


def square():
    for i in range(4):
        forward(100)
        right(90)


def square():
    for i in range(3):
        forward(100)
        right(120)


square()

To make all three squares half as big now, how many numbers change?

Match each part of the program with its job.

def square():
square()
for i in range(4):
forward(100)

Put the lines in order so the program draws one square.

Pieces (click to add)
    Your program

      Someone pasted a second def square below the first. What does square() draw?

      ModifyChange the code on purpose and check the result.

      Modify

      Change the size of the square inside def square(): and run it.

      Need a hint?

      Change a number inside the def, not the call.

      Write def triangle(): following the pattern of square.

      Need a hint?

      Copy the pattern of square: the word def, a name, brackets, a colon, then the indented steps.

      Another hint

      A triangle has 3 sides. The turn at each corner is not 90.

      Draw a square, then a triangle, then a square again.

      Need a hint?

      Call each function by its name with brackets, like square().

      Try it yourselfYour edits are saved in this browser.

      Write def triangle() and run your program.

        Run your program. This ticks when your code does all of the above.

        Call square twice and triangle at least once.

          Run your program. This ticks when your code does all of the above.

          InvestigateTrace how each line of code connects to what you see.

          Mix it up

          Work this out on paper first.

          def square():
              for i in range(4):
                  forward(100)
                  right(90)
          
          square()
          square()
          square()
          

          The program above calls square three times. How many times does forward(100) run altogether?

          MakeBuild something new using what you have learned. Expect a few tries; that is normal.

          Make

          Write a function that draws any shape you like (a rectangle, a hexagon, a star), then call it three times in a row.

          Try it yourselfYour edits are saved in this browser.
          Need a hint?

          Start with a shape you can already draw with a loop, then put def name(): above it.

          Write your function and call it three times.

            Run your program. This ticks when your code does all of the above.

            ModifyChange the code on purpose and check the result.

            Extend the house plan

            A house plan is a few small named pieces: wall() and roof(). Run it. Then add a door() function and call it. Notice that you never edit wall or roof to do it.

            Try it yourselfYour edits are saved in this browser.
            For teachers

            Students give a group of steps a name with def, then use that name again and again, and see why one change inside a function updates every use. About 50 minutes.

            Open the teacher guide: answers, solutions, slides and a worksheet.

            Students will be able to

            Before class

            Read the unit primer "Functions in 5 minutes" first. Then run the def version and write the triangle function yourself. The surprise for students: def square(): on its own draws nothing. It only describes the steps; square() runs them.

            Running the lesson

            1. Predict and Run: the copy-and-paste program works, but making the squares smaller means changing three numbers. Let students feel that.
            2. Investigate: introduce def as 'teach Python a new word'. def square(): teaches it; square() uses it. Ask: what does the program draw if we delete the three square() lines?
            3. The match task separates describing (def) from doing (calling). Spend time here: it is the idea everything else builds on.
            4. Modify: students write triangle by copying the pattern of square. Check they call it as well as define it.
            5. Make: any shape is fine. The check is a def and three calls.

            The hard part (on purpose)

            A def on its own does nothing until it's called. When nothing draws, ask where the function is called.

            When students get stuck

            Stretch and support

            Stretch: Write a function star() (five lines, turning 144 degrees each time) and use it to draw a row of stars.

            Support: Give the def square() code and ask students only to add a triangle() below it by copying and changing two numbers.

            Where it leads

            Next lesson gives functions inputs (parameters), so one function can draw many sizes. Every app is built from named functions. Class ideas: each student writes one shape function and the class combines them into a picture; time how long it takes to change three copies versus one function.

            What each step is for

            Now you can
            Next lesson3. Functions with parametersMake one function draw many different shapes, and keep your best ones as tools.