Python Function
A Python function is a named block of code that runs when it is called. def begins the definition, the name follows, parameters go in parentheses, and a colon opens an indented body. A def statement creates and binds a function object and evaluates any default expressions. The body of an ordinary function runs on a call such as total_seconds(1, 30, 0).
return ends the call and hands a value back to the caller, which can store it, pass it on, or format it. print() is different: it displays a value and returns None, so its displayed number is not its return value. A function whose body ends without return, or that runs a bare return, returns None. Comma-separated expressions written after return arrive as one tuple.
Python distinguishes built-in functions, which come with the language and need no import (print(), len(), sorted(), min()), from functions you define and from those a module provides. An instance method is bound to an object: text.replace retrieves that bound method, and text.replace("a", "b") calls it on text.
Two habits keep functions useful. Give the function a name that says what it produces, and keep it to one task, so its result can be checked against known inputs. Take what the work depends on as parameters instead of reading values defined elsewhere; a function that reads a notebook-level name changes behavior when that name changes, so tests must set up and restore that outside state.
References: Defining functions, Built-in functions. See it in use in Python Functions, Modules, and Classes.
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
