Python Tutorial: Functions
Write once, run anywhere. Functions are the building blocks of every real program.
Stop repeating yourself
In Chapter 7 you wrote loops for repetition. But what if the same logic is needed in five different places?
Functions let you name a block of code and call it anywhere. The same code runs without copying it. Twelve steps.
What you'll learn in this Python functions tutorial
This interactive Python tutorial has 11 hands-on exercises. Estimated time: 22 minutes.
- Stop copying code — Imagine you need to validate an email address in 10 different places in your program. Without functions, you copy the sa…
- Define your first function — A function definition:
- Parameters — give it input — A function without input can only do one thing. With **parameters**, it can do that thing with different data each time.
- return — give something back — So far your functions print things. But printing inside a function isn't always useful — sometimes you want the **result…
- Default values — optional parameters — Parameters can have default values. If the caller doesn't provide one, the default is used:
- *args — any number of arguments — What if you don't know in advance how many arguments someone will pass?
- **kwargs — named arguments — `**kwargs` captures any number of keyword arguments as a dictionary:
- lambda — a function in one line — Sometimes a function is so simple it feels wasteful to write a full `def`.
- Closures — functions that remember — A closure is a function that **remembers** variables from the scope where it was created — even after that scope is gone…
- Recursion — a function calling itself — A recursive function calls *itself*. It sounds circular — and it is, but in a controlled way.
- Build a calculator — Final challenge — no starter code.
Python Functions concepts covered
- Stop repeating yourself