Importing, using and creating libraries in Python

--Originally published at Programming

Importing and using Module/Library

A module (also called library) is a file containing Python definitions and statements. Python has many modules we can import. For example, when we need to use the trigonometrical sin() or cos() functions or we need to use the constant number pi we can import the module math using the import statement to use that module’s functions. So if we want to import the math module we would have to do something like this.

1.png

Inside the module math there are many different functions that can be used, whenever you want to use one of them you just need to type the library followed by a dot and the name of the function you want to use. See the example below where we print to the console the result of sin(3)

*Notice that all trigonometrical functions take only radians as parameters and NOT degrees

1.png

Creating your own libraries

Now that you know how to import libraries in Python it’s time for us to take the next step and start making our own libraries, which will contain functions created by ourselves. Let’s say you are working on a project that requires several functions to get the area of some geometrical figures. Either you can create those functions within the file you are working on or you can have a separate file containing the functions. Let’s take a look at how it’s done. On the upper left side of your eclipse screen you have your modules (.py files), folders and packages as shown in the picture below.

2.png

Imagine that you are working with the Exercices2.py module (Sorry for the bad spelling). Now you are going to create another module within the folder FirstPartial. For the purpose of this example, I’m going to name the module mathAreas.py

3.png

And now I’m

5.png
6.png
to write some functions inside mathAreas.py to get the area of a circle, square, rectangle and triangle as shown in the picture below.

5.png

Now let’s return to the Exercices2.py module, we are going to use the import statement and select mathAreas. And then we are going to write some code to prove that the functions within mathAreas really work. We are going to print to the console the area of a rectangle whose sides are 4 cm x 10 cm.

6.png

Great! Now you know how to create your own libraries and import them. Keep the good work and I see you in the next blog post.