Having started writing a chapter about OOP, I realized that I had completely forgotten to consecrate such a large and necessary section of Python as a function. The topic is large and extensive, because in order not to stretch the pause between lessons much, I decided to divide it into 2 parts. First, I will tell the basics, then the in-depth features of the Python function.
Functions in Python are declared not easy, but very simple. Here is an example of the simplest:
def empty_func ():
pass
The announcement begins with the keyword def, which is not difficult to guess is short for define. After it comes the name of the function. After the name in parentheses, a list of parameters is specified, in this case missing.
The function body is indented with the next line. Note that in Python, functions with an empty body are prohibited, because the “empty operator” pass is used as the body of the above function.
Now consider the example more seriously.
')
def safe_div (x, y):
"" "Do a safe division :-)
for fun and profit "" "
if y! = 0:
z = x / y
print z
return z
else:
print "Yippie-kay-yay, motherf___er!"
In this example, there are several innovations. The first thing that catches your eye is the docstring that comes right after the function body.
Usually this line takes more than one line of the source text (sorry for the pun) and therefore is given in triple quotes. It is intended to describe the function, its purpose, parameters, etc. All good IDEs can work with this line. You can get access to it from the program itself, using the __doc__ property:
print safe_div .__ doc__
This property (yes, yes, it is a property, in Python even the functions are actually classes) are convenient to use during the sessions of the interactive console.
>>> from ftplib import FTP
>>> print FTP .__ doc__
An FTP client class.
To create a connection, call the class using this argument:
host, user, passwd, acct
These are all strings, and have default value ''.
Then use self.connect () with the optional host and port argument.
# Further I tinker :-)
Let's return to our original function. Its essence is very simple, it takes 2 parameters: x and y. If y is not 0, it divides x by y, displays the result on the screen and returns its quotient as a result. The result of the function is returned using the return command. Thanks to the tuple mechanism described in the last lesson, functions in Python can return multiple objects at once.
If the divider is still zero, the function displays an error message. It would be wrong to assume that in this case the function will not return anything. It would be more correct to say that the function returns “nothing” :) In other words, if there is no return operator in the function, or it is called without parameters, the function returns the special value None. You can easily verify this by calling something like print safe_div (10, 0).
Here is a slightly more complicated example; it is taken from the presentation of Guido van Rossum.
def gcd (a, b):
"Finding NOD"
while a! = 0:
a, b = b% a, a # parallel definition
return b
This function finds the greatest common divisor of two numbers.
In general, it should be noted that the parameters in the Python function are passed by reference. Another, perhaps non-trivial fact that one has to get used to is the fact that the functions themselves are a value that can be assigned. If you use our safe_div function for further experiments, you can write the following code.
mystic_function = safe_div
print mystic_function (10, 4)
This time and all, “overboard” there are still many aspects of the definition of functions in Python, which will be covered next time.
Exercises to test.
1. Based on the existing function of finding the GCD, write the search function for the LCM of two numbers.
2. Write a subroutine for tabulating the function passed in as an argument. The arguments also specify the initial, final value and the tab step.
PS By the way, what is the optimal amount of "lesson"? Which is better - less often big chapters, or “better less and more often”.