Modules, what the heck are those things?
In python, modules are independent files that contain functions. These functions can be called in the file you are importing the modules. It is an easy way to keep functions outside your files, and it’s very useful when creating large code files.
To import a module into a file, guess what, you use import modulename, yeah, as simple as that.
From that file, you can use all the functions.
Here is
How to create a module
Since a module is justa file with only functions and statesments,so for your module you’d wish to have only those to make it easy.
In my module I am going to have two functions, one for fibonacci, that can be seen in this QUIZ, and one for getting the distance between two points, in this QUIZ.
So i just take the functions and store them in the file, just like this
I chose to name the module fibdist, just as there:
And that’s it, I have just created my own module named fibdist!
Import a module and use it
As I said, to import is just, well, import and the name of the module WITHOUT the extension, in my case will be import fibdist
My module is already set in my file, so now I want to create a proggram that asks the user if he wants to do a fibonacci test or to get the distance between two points,
Then, I can do all my coding, if it is 1 is fibonacci, is 2 is distance and so on
So here is the important part, in order to use the functions see right there, in the lines 8 and 18, I am using the function from the modules
To do that, the correct format is
modulename.functionname(parameters)
The tricky part here is that you need to know what the name and the parameters of the function are in order to use them correctly.
As you can see, it is really easy, and with that you can use those functions anytime you need to, that’s why modules are awesomly powerfully great!
As always
Masteries 13 and 14: Modules by charliegdrummer is licensed under a Creative Commons Attribution 4.0 International License.