How collections work in Python

Use modules in Python

In the last few chapters we have been busy creating functions.

We could simply insert them into new projects again and again using “copy-and-paste”. Several things speak against this. Our code is unnecessarily inflated, since we would have to integrate the code in every program file (and a program can consist of several files) and errors "multiply" so diligently and the elimination is correspondingly time-consuming. The best argument is that there is a much easier way to do it.

Now it would be very practical to have all of our functions in one file, which we use over and over again in our projects. It's very easy to do in Python. In Python one speaks of modules. If we take a look at the use of modules, the advantages are easy to grasp and understand.

There is also the command. It is important that both files are in the same directory. First, let's create our function collection in the “” file. In our collection of functions we have 2 example functions that we assume that we will need over and over again and in different projects. First the function that we created in the last chapter as an example for return values ​​and a function for greeting.

The function from the last chapter:

And our greeting function (there is a card game that uses this greeting).

We save these two functions in the “” file. If we were to run the Python program, absolutely nothing would happen because the functions are defined, but they are not called. We want to do this from another program file.

Our file, which uses our function collection, must be in the same directory as our file "".

In the first step, we will import the function collection in the new file “example deployment”. It is important here that the file name is entered without spelling mistakes and without the ending “.py”!

Now, of course, you could get the idea of ​​simply calling the function in our new files. That would result in an error message. We also have to specify the module!

This information is made via the link with the point:

The transfer and return values ​​are used as usual. Only the reference to the module with the point link remains. So it is always clear where a function comes from, if you still need changes or extensions to your universal function collection.

That was the use of modules in Python.

Recommend • Social Bookmarks • Thank you