Python: Create, Import, and Use a Module

Today we are going to cover what I consider a flaw in the iPython Notebook environment. Code you write cannot be imported into another program like you can using just a standard Python compiler. At least it cannot under its native .ipynb format.

For this example, we are going to use the Spyder IDE that comes with Anaconda. You can use any IDE you want, in all honesty, you can use a simple notepad editor to do this if you don’t have Spyder installed.

 

Create a Module

I am going to create a little module called math_bl.py. This module contains 3 simple functions: sqr2, sub2, and add2

 

 

In my instance, my iPython notebooks are stored under my user directory. If you are not sure where you notebooks are, you can use the pwd command (print working directory). This will tell you where to save your math_bl.py file to.

pyModu3.jpg

** note the double \\ are due to a formatting function in Python. \ is a break command that can be used for many purposes. Example \t means to insert a tab.

pyModu4.jpg

So effectively you have to use \\ if you want a \ in Python, making my working directory C:\Users\Benjamin  

Import the Module

Now if I open up a new notebook and try using the functions I have just created, I will error out.

So, what I need to do is import add2, then I can start calling on the functions I created in add2


If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Next Lesson: 

Return to: Python for Data Science Course

Follow this link for more Python content: Python

Leave a Reply