← Python functions and events

Functions that decide

Put an if inside a function so it chooses its answer, then call it for every item in a list: decisions, lists and functions working together.

Apps decide all the time: is this message spam, is this score a pass, which colour is this weather? Each is a function with an if inside.

You know three things that work well together: if chooses, lists hold many values, and functions give answers back. Put them together:

def size_colour(size):
    if size > 50:
        return "red"
    else:
        return "blue"

The function decides its answer. Call it inside a loop over a list, and it decides for every item.

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

decide.py
from turtle import *


def size_colour(size):
    if size > 50:
        return "red"
    else:
        return "blue"


print(size_colour(80))
print(size_colour(30))

Each call gives back one of two words. Which one depends on the size.

What two words are printed?

RunRun it and compare the result with your prediction.

Run

Run it. Each dot is as big as its size, and the function chose its colour. Change 50 to 30 and run again: which dots change?

decide.py
from turtle import *

speed(0)


def size_colour(size):
    if size > 50:
        return "red"
    else:
        return "blue"


sizes = [20, 60, 35, 80, 50]

penup()
goto(-160, 0)
for s in sizes:
    dot(s, size_colour(s))
    forward(80)
Try it yourselfYour edits are saved in this browser.

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

Investigate

decide.py
from turtle import *

speed(0)


def size_colour(size):
    if size > 50:
        return "red"
    else:
        return "blue"


sizes = [20, 60, 35, 80, 50]

penup()
goto(-160, 0)
for s in sizes:
    dot(s, size_colour(s))
    forward(80)

What does each size give back?

One decision, many uses.

A count that keeps starting again.

Fill in what size_colour gives back for each size in the list.

ssize_colour(s)
20blue
60red
35
80
50

Why put the if inside a function, and not straight in the loop?

There are two sizes over 50, but this prints 1. There is no error. Click the line that is wrong.

ModifyChange the code on purpose and check the result.

Modify

Add an elif.

Need a hint?

elif adds another choice between if and else.

Another hint

elif size > 30: return "orange", between the if and the else.

Count with a loop and an if.

Need a hint?

A function that counts: start at 0 before the loop, add 1 inside an if, return the count after the loop.

Another hint

def count_big(sizes): then count = 0, for s in sizes:, if s > 50: count = count + 1, and return count. Then print(count_big(sizes)).

Try it yourselfYour edits are saved in this browser.

Give middle sizes (over 30) their own colour, orange.

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

    Write def count_big(sizes) that returns how many sizes are over 50, and print it.

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

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

      Score bars

      Draw a bar for each score, as tall as the score, coloured by a function you write: green for 70 or more, orange for 50 or more, red below that. Most people need two goes at the bars: draw one bar first, then loop.

      Try it yourselfYour edits are saved in this browser.

      Write a function that returns a colour for a score, and use it to colour a bar for every score.

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

        For teachers

        Students write a function with an if inside that chooses its answer, call it for every size in a list to colour dots, trace its decisions, find a counter reset inside the loop, add an elif and a counting function, and colour score bars. About 50 minutes.

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

        Students will be able to

        Before class

        A revisit lesson: nothing in it is new. If and else, lists, for-each and functions that return come together: an if inside a function, with return in each branch, so the function chooses its answer; then a loop over a list calls it for every item. Students who found if or lists shaky get them again in a new place, which is the point.

        The planted bug is the classic counting slip: count = 0 inside the loop resets the count every time round. The trace has one edge case on purpose: 50 is not more than 50.

        Running the lesson

        1. Predict: ask students to read the function aloud as a sentence: if the size is over 50, give back red, otherwise blue.
        2. Run: change 50 to 30 and ask which dots changed and why.
        3. Investigate: do the trace before running anything; argue about 50.
        4. Modify: for count_big, ask "when should count start at 0: once, or every time round?"
        5. Make: ask students to draw one bar first, then wrap it in a loop.

        The hard part (on purpose)

        The counter is where students struggle: they put count = 0 wherever it fits. Ask them to trace the loop with a table on paper (s, count) before changing a line.

        When students get stuck

        Stretch and support

        Stretch: Write is_even(n) that returns True or False, and use it to draw only the even-numbered dots. Return a size as well as a colour from two functions.

        Support: Give the counting function with count = 0 missing; students decide where it goes.

        Where it leads

        Next lesson: modules, a place to keep useful functions such as size_colour. The same pattern (a function that decides, called for each item) appears in Catch the turtle's hit test and in the console bridge's menus.

        What each step is for

        Now you can
        Next lesson6. ModulesKeep related functions together in a file you can import, like a toolbox.