Function Machine
Run the Function Machine MicroSim Fullscreen
Edit in the p5.js Editor
About This MicroSim
A function takes input values called arguments, assigns them to its parameters, runs its body, and hands back a return value. Picturing a function as a machine with input chutes and an output chute helps make the difference between parameters (the chute labels) and arguments (the tokens you drop in) concrete.
Choose a function from the menu: the chapter's to_12_hour(hour24), split_seconds(total) (which returns a tuple of three values), or add(a, b). Type the arguments and press Run: the tokens drop into the chutes, the gears turn, and the return value slides out. The code card shows the def and the call. Pick Write your own to type a one-line lambda such as lambda m: m * 60. For safety, the machine only understands numbers, the parameter names, + - * / // %, parentheses and commas.
This MicroSim supports the chapter Control Flow, Functions, and Modules.
How to Use
- Pick a function from the menu. Its definition appears in the code card.
- Type a number for each argument in the boxes below the menu.
- Press Run and watch the tokens go in and the return value come out.
- Choose Write your own (lambda), type a lambda in the bottom box, set the arguments and press Run. Error messages explain any problem.
Iframe Embed Code
You can add this MicroSim to any web page by adding this to your HTML:
1 2 3 4 | |
Lesson Plan
Learning Objectives
Students will be able to:
- Explain a function as a machine that turns arguments into a return value
- Match each argument to the parameter name it is assigned to
- Create a one-line lambda function and test it with different arguments
Grade Level
9-12 (high school)
Duration
10-15 minutes
Prerequisites
- Arithmetic operators including // and %
- Variables and assignment
Activities
- Exploration (4 min): Run
to_12_hourfor 0, 9, 12, 13 and 23. Write down each result. - Guided Practice (6 min): Run
split_secondsfor 3600, 3661 and 45296. Explain why it returns three values. - Create (5 min): Write your own lambda that turns minutes into seconds, and one that takes hours and minutes and returns minutes since midnight.
Assessment
- Students predict
to_12_hour(0)andto_12_hour(12)before running them. - Students write a working two-parameter lambda.
- Students explain the difference between a parameter and an argument using the chute picture.
References
- Python Tutorial: Defining Functions - official introduction to def and return
- Python Tutorial: Lambda Expressions - official introduction to lambda
- Function (computer programming) - Wikipedia article on functions