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 itreturn— sends a value back out; a function with noreturngives backNone- Scope — a variable created inside a function only exists inside that function
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:
- A worked example, fully written out
- Two guided practices — change a few values, then fill in some blanks
- Two independent practices — write your own from scratch, different scenario each time
- An optional stretch, if you want to go further
- 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.
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.