Defining Functions, Parameters & Return Values
You'll learn to
- -Define a function with `def` and call it with positional arguments
- -Understand what a function returns when it has no explicit `return`
- -Return multiple values from a single function using a tuple
Every program you have written so far has been a single, flat sequence of statements. Functions are the first tool for breaking that sequence into named, reusable pieces - and every Forge Algorithm Lab level you will eventually submit is, at its core, one or more functions (or methods, which are just functions that live inside a class) that the evaluator calls with specific inputs and checks the output of. Getting comfortable with parameters and return values now pays off immediately.
Defining and Calling a Function
A function is defined with `def`, a name, a parenthesized list of parameters, and a colon, followed by an indented body - the same indentation rules that govern `if` blocks and loops apply here.
`a` and `b` are parameters - placeholders in the definition. `3` and `4` are arguments - the actual values supplied at the call site. This distinction rarely matters in casual conversation, but it becomes precise and important once default arguments and keyword arguments enter the picture in the next chapter.
What Happens Without a Return Statement
A function does not have to return anything explicitly. If execution reaches the end of the function body without hitting a `return` statement - or hits a bare `return` with no value - Python returns `None`. This is a frequent source of confusion: calling `print()` inside a function shows output on the screen, but it does not hand a value back to the caller.
This is one of the single most common bugs in beginner Python code, and it shows up constantly in graded lab submissions: a function that `print()`s the right-looking answer but returns `None`, so any code (or evaluator) that calls it and checks the return value fails silently.
Returning Multiple Values
Python lets a function return more than one value by packing them into a tuple. This uses the same tuple-unpacking syntax you already know from earlier chapters - `return` builds the tuple, and the caller can unpack it directly into separate names.
- -`return a, b` is really `return (a, b)` - the parentheses are optional for tuples.
- -A function can only have one `return` statement execute per call - once a `return` runs, the function exits immediately, even mid-loop.
- -Calling `return` with no value, or omitting `return` entirely, both produce `None`.