Functions

You've been writing the same kind of code over and over — reading input, calculating damage, printing a message. Functions let you package that up once, give it a name, and reuse it — the first real step toward organizing a program instead of just writing it top to bottom.

What You'll Learn

  • def — creates a function; anything in parentheses is a parameter, a value the function needs from whoever calls it
  • return — sends a value back out; a function with no return gives back None
  • Scope — a variable created inside a function only exists inside that function
Watch out for: print()-ing inside a function shows something on screen, but doesn't give the calling code anything to work with afterward. If you need to use the result later, you need return, not just print().

Today's Activity

Today's practice happens inside the notebook below — work through it top to bottom:

  1. A worked example, fully written out
  2. Two guided practices — change a few values, then fill in some blanks
  3. Two independent practices — write your own from scratch, different scenario each time
  4. An optional stretch, if you want to go further
  5. One check-your-understanding question to close

Download the notebook, save it into your 1_foundations folder in your cloned repo, and open it in VS Code. Commit once you've saved it, then commit again when you're done for the day.

Download 1.6_Functions.ipynb

New to notebooks? See Using Jupyter Notebooks first.

What's Next

Coming up: Project 1B — The Adventure Loops, where you turn your one-shot decision into a multi-room adventure.