Python Functions: def, Parameters and return
A function packages a piece of logic under a name so you can run it whenever you need it, with different inputs each time. Functions are the main tool for keeping programs short, readable and testable. You have been calling built-in ones like print() and len(); now you will write your own.
Defining and calling
def greet(name): starts a definition. name is a parameter: a local variable that receives whatever value the caller passes, which is called an argument. The indented body runs only when the function is called, as in greet("Noah"). Defining a function does not run it.
return sends a value back to the caller and ends the function at once. The caller can print it, store it or pass it on. A function without a return, or with a bare return, gives back the special value None. That is why result = log("saved") stores None: log prints but does not return. Printing and returning are different things, and mixing them up is the classic beginner bug.
Expected output
Hello, Noah! 12 LOG: saved None 4 16 10.75 Return a friendly greeting.
Returning several values
stats() returns three values separated by commas. Python packs them into a tuple, and the caller unpacks them into low, high and mean. This is the normal way to return more than one result.
Scope
Names assigned inside a function are local: they exist only while the function runs and do not affect variables with the same name outside. A function can read global names, but relying on that makes code harder to follow. Pass data in as arguments and return results instead.
Docstrings
A string literal on the first line of the body is the function's docstring. It documents what the function does, and Python stores it in greet.__doc__, where help(greet) and code editors can find it. Write one for every function that is not obvious from its name.
Common mistakes
- Forgetting the parentheses:
greetrefers to the function;greet()calls it. - Printing inside a function when the caller needs the value. Return it instead.
- Calling a function before the
defline has run, which raisesNameError.
Summary
def name(params):defines a function; calling it runs the body.returnhands back a value; without it the result isNone.return a, breturns a tuple that callers can unpack.- Variables created inside a function are local to it.
Quiz: Functions