You have already used many built-in functions (int, float, print, input, type, sum, len, min and max) and a few functions from the statistics module (mean, median and mode). Each performed a single, well-defined task. You’ll often define and call custom functions. The following code segment defines a square function that calculates the square of its argument. Then, it calls the function twice — once to square the int value 7 (producing the int value 49) and once to square the float value 2.5 (producing the float value 6.25):
def square(num): """Calculate the square of number.""" return num ** 2; result = square(7) print(result) result = square(2.5) print(result)
The statements defining the function are written only once, but may be called “to do their job” from many points throughout a program and as often as you like. Calling
square with a non-numeric argument like “hello” causes a TypeError because the exponentiation operator works only with numeric values.
Defining a Custom Function:
A function definition begins with the
def keyword, followed by the function name, a set of parentheses and a colon. Like variable identifiers, by convention function names should begin with a lowercase letter and in multiword names underscores should separate each word. The required parentheses contain the function’s parameter list. The parameter list is a comma-separated list of parameters representing the data that the function needs to perform its task. Function
square has only one parameter named number – the value to be squared. If the parentheses are empty, the function does not use parameters to perform its task. The indented lines after the colon (:) are the function’s body, which consists of an optional docstring followed by the statements that perform the function’s task. We’ll soon point out the difference between a function’s block and a control statement’s suite.
Specifying a Custom Function’s Docstring
The Style Guide for Python Code says that the first line in a function’s block should be a docstring that briefly explains the function’s purpose: “””Calculate the square of number.””” To provide more detail, you can use a multiline docstring – the style guide recommends starting with a brief explanation, followed by a blank line and the additional details.