CoursesAIMathCodePhysicsAbout and FAQ

TwiddleLab / Code / How a Programmer Thinks

Functions: Name a Recipe

Lesson 9 of 10 · 7 min · Free, no account needed

What you will learn

  • A function is a named recipe: def gives the name and the steps.
  • Parameters are the boxes in the recipe; arguments are the values you pass in a call.
  • return sends the result back to the place that called it. Without return, you get None.
  • Change the function once, and every call uses the new version.

Start the lesson

How the lesson goes

  1. A game uses the same damage formula in 50 places.

    The designer changes the 2 to a 3. Tap each place to fix it.

  2. What does this print?

    Drag your bet into the output.

  3. Step through the call.

    Watch 10 and 3 fly into the function, and the answer fly back.

  4. The parts of a function have names.

    A function is a named recipe. def starts it: the name, then the parameters in brackets, then a colon.

    Parameters are boxes inside the recipe, here n. Arguments are the values you pass when you call it, here 21.

    return sends the result back to wherever the function was called. Watch double(21) run.

  5. Game: exact hits.

    Each enemy has some health. Set the arguments so one hit takes exactly all of it. Par: 3 hits.

  6. Design your own streak bonus.

    5 coins per day. From 7 days on, add a bonus. Pick one bonus line, put the lines in order, Run.

  7. Python functions are math functions.

    Drag each Python function to the math rule it computes.

  8. This prints None instead of 16.

    Run it, find what's missing, fix it.

  9. What does damage(4, 2) return?

  10. Your streak bonus now runs 50 places in a game.

    Tap a number in your function and pick a new one.

Previous lesson: Finding Things Fast · Next lesson: Build a Mini-game · Part of the course: How a Programmer Thinks

Lessons are interactive and need JavaScript. Turn it on to play them.

Loading TwiddleLab