Python functions
We are able to create our own Python functions. Use the interpreter, generally, if you only need to do a calculation once. However, when you or others need to make a specific type of calculation repeatedly, define a function (phyton functions). The compound command is an easy illustration.
To examine the folders in your search path, type echo $PATH. To find your Python program, type which python; this should match the first line in your script.
>>> def f(x): ... return x*x ...
defines the squaring function f(x) = x2, a common illustration used in early mathematics classes. The definition’s first line is the function header, which contains the function’s name, f. The function’s body, where the output value is calculated, is presented in the following lines. The return of the solution is the last stage, without which we would never witness any outcomes. In keeping with the example, we may employ the function to determine the square of any input:
>>> f(2) 4 >>> f (2.5) 6.25
Python functions
The name of a python function is purely arbitrary. We could have defined the same python function as above, but with the name square instead of f; then to use it we use the new function name instead of the old:
>>> def square (x): ... return x*x ... >>> square (3) 9 >>> square (2.5) 6.25
In reality, a function name is not entirely arbitrary because we are not permitted to use a reserved word in the name of a function. The reserved words in Python are: and, def, del, for, is, raise, assert, elif, from, lambda, return, break, else, global, not, try, class, except, if, or, while, continue, exec, import, pass, and yield. By the way, Python also gives us the option to define functions using a syntax akin to the mathematical logic’s Lambda Calculus. Alternative definitions for the aforementioned function include the ones below:
>>> square = lambda x: x*x
This lambda x: An example of a lambda expression is x*x. Lambda expressions come in handy when you need to declare a function in a single line and when you don’t want to name it but still need it.
Function definitions are often kept in a module (file) for future usage. From the user’s point of view, these are identical to Python’s Library modules.