← Python functions and events

Python functions and events: recap

Answer each question in your head or on paper first, then check it.

Start from a working program

1. Read a program

Try firstIn the garden, which part would you change to make every flower head the same size?

Check your answer

The update head = head + 4. Remove it, or set head once and never add to it.

A longer program is made of parts that each do one job: a decision, a calculation with the counter, an update, a list item picked by its place. Read for the job first, not every symbol. Then change only the part that does the job you want to change.

Open the lesson →

Functions

2. Functions

Try firstA program has def square(): with a loop inside, and nothing else. What does it draw, and why?

Check your answer

Nothing. The def only describes the steps; the function has to be called with square() to run them.

A function is a named set of steps. def square(): teaches Python a new word, square, and the indented lines say what it means.

Writing the def does not draw anything. The steps run when you call the function by its name with brackets: square(). Call it three times and you get three squares.

The big win: if you want smaller squares, you change the number inside the def once, and every call changes with it. No hunting for copies.

def teaches Python a new word; calling it runs the steps · Sound on for the voiceover
Open the lesson →

3. Functions with parameters

Try firstdef polygon(sides, size): ... What does polygon(5, 40) draw?

Check your answer

A pentagon (5 sides) with each side 40 steps long, turning 72 degrees at each corner.

A parameter lets a function take an input. In def square(size):, size is a placeholder. When you call square(50), the 50 goes into size and the function draws with it.

A function can have several parameters: polygon(sides, size). The values you pass, called arguments, fill the parameters in order: polygon(6, 80) means 6 sides, 80 long.

Functions can use other functions. pattern calls polygon again and again, turning a little each time, to make something bigger from a small piece.

A parameter lets a function take an input · Sound on for the voiceover
Open the lesson →

4. Functions that give answers

Try firstdef double(n): return n * 2. What does forward(double(30)) do?

Check your answer

double(30) gives back 60, so the turtle moves forward 60 steps.

Some functions do something (draw a square). Others give an answer back. return m * scale hands the result to whoever called the function.

So forward(metres(5)) works in two steps: first metres(5) is worked out and gives back 100, then forward(100) runs.

print is different: it only shows a value on the screen. The program cannot use a printed value. If a function prints instead of returning, the caller gets nothing back (Python calls it None).

return hands an answer back to the caller · Sound on for the voiceover
Open the lesson →

5. Functions that decide

Try firstdef grade(score): if score >= 50: return "pass" else: return "try again". What is grade(50)?

Check your answer

pass: 50 is greater than or equal to 50.

  1. An if inside a function lets it choose its answer: sizes over 50 give back red, the rest blue.
  2. A loop over a list asks the function about every size.
  3. Each dot gets the colour the function chose.
An if inside a function lets it choose its answer · Sound on for the voiceover
Open the lesson →

6. Modules

Try firstTwo programs each have their own copy of a draw_tree function with a bug. Why would putting draw_tree in a module be better?

Check your answer

Both programs would import the one function, so fixing it once in the module fixes it for both.

A module is a file of related functions that any program can use. from shapes import square brings the square function from the file shapes.py into your program.

Why bother? If you copy a function into two programs and later find a bug, you must fix both copies, and it is easy to miss one. With a module there is one copy, so you fix it once.

A module should only hold the functions (the def blocks). The program that imports it does the calling.

A module is a file of functions any program can use · Sound on for the voiceover
Open the lesson →

Interaction

7. Events

Try firstWhat is the difference between onscreenclick(stamp) and onscreenclick(stamp())?

Check your answer

onscreenclick(stamp) hands the function over to run on each click. stamp() with brackets runs it straight away, once, which is wrong here.

Most apps spend their time waiting for something to happen: a tap, a key, a timer. When it happens, they run a function.

onscreenclick(stamp) says "when the picture is clicked, run stamp". You hand over the function's name, with no brackets. The computer runs it later, for every click, and tells it where you clicked (x and y). A function handed over like this is called a callback.

mainloop() keeps the program waiting for events. It runs until you press Stop.

The program waits for a click, then runs a function · Sound on for the voiceover
Open the lesson →

8. Build a button

Try firstA button has bx = 0, by = 0, bw = 100, bh = 40. Is a click at (50, 50) inside? Why?

Check your answer

No. x = 50 is between 0 and 100, but y = 50 is above the top edge (0 + 40 = 40).

A button on a screen is really three things: a rectangle drawn on the screen, a label, and a check that asks "did the click land inside the rectangle?"

The check uses four comparisons. A click at (x, y) is inside when x is past the left edge and before the right edge, and y is above the bottom and below the top. All four must be true, so they are joined with and.

When the check passes, the program changes something (adds to a count) and redraws the screen to show it. Every app's buttons do this behind the scenes.

A button is a rectangle, a label and a check · Sound on for the voiceover
Open the lesson →

Final challenge: Catch the turtle

9. Catch the turtle

Try firstA catch game scores a click with if showing and inside(x, y):, where showing is True only while the turtle is on screen. Why check showing as well as inside?

Check your answer

So a click only scores while the turtle is visible. After it hides, clicking its old spot should not count.

A game is a few rules, some data and a loop. Here the data is the score, the turtle's spot and whether it is showing. The loop is the timer that makes the turtle hop every second. The rules are what each click and each hide means.

showing is either True or False. It remembers something that changes: is the turtle on screen right now? Each event checks it before deciding what to do.

The path is two lists of numbers. Because the turtle follows a pattern, you can predict where it will go next, and that is how good players win.

A game is a few rules, some data and a loop · Sound on for the voiceover
Open the lesson →

10. Power-ups

Try firstName one part of your game that is user interface and one that is a game rule.

Check your answer

For example: the status bar is user interface (it shows the state); losing a life on a miss is a game rule.

Games and apps are built from the same two kinds of parts. The user interface is what you see and use: the status bar, the buttons. The rules decide what each event means: a miss loses a life, a gold turtle is worth 5, an upgrade costs 5 points.

label(x, y, name, value) is one function that draws one part of the status bar. Calling it three times draws Score, Lives and Time, with no copied code.

A good power-up has a fair cost: strong enough to want, expensive enough to think about.

Games are built from an interface and rules · Sound on for the voiceover
Open the lesson →