Functions
Functions
🎯 By the end of this lesson
After finishing this lesson, you will be able to confidently do the following three things.
- ▸✅ args · *kwargs + the default-value trap (mutable default)
- ▸✅ Write type hints + docstrings
- ▸✅ First-class functions + closures
Keep the learning goals as a checklist, and close the lesson once you can answer all of them.
8 Function Patterns — Code + Output
A function = a named block of code. It can be reused whenever the same task needs to be performed multiple times.
1. The Simplest Function
def (define) → function name → ( ) → : → indented block.
2. Accepting Parameters
name = parameter (a slot to receive a value). `
💡 Key Points
1. Parameters with default values must be placed at the end.
2. *args: variable positional arguments (tuple)
3. **kwargs: variable keyword arguments (dictionary)
Python file I/O uses the open() function to open files. The with open(path, mode) as f: pattern guarantees the file is automatically closed. Modes: r (read), w (write), a (append), b (binary). Use json.load/dump for JSON and csv.reader/writer for CSV. pathlib.Path handles file paths in an object-oriented way.
🐍 Try It Out — Functions
🤖 Try Asking AI Like This
Knowing the concepts in this lesson lets you give specific instructions to AI. Instead of a vague "fix this," you can make vocabulary-driven requests — and that is where token savings begin.
- ▸"Add type hints + a docstring to this function."
- ▸"Remove the side effects (global variable mutation) from this function and convert it to a pure function."
Why This Reduces Tokens
Without knowing the concepts, you have to ask "What does that mean?" after every AI response. Those follow-up questions consume tokens. Learn the concept once, and the conversation ends in a single exchange.