Python for Beginners 10: Creating Modules

Since we already know how to use modules or libraries in Python3, we can create our own. Actually, this is very simple because you can import any file that contains Python code as a module. The only thing that you need to be aware of is the name of your file: It may not contain any blank spaces.

Since it is so basic, we can start away with practicing. Remember our typical example of the temperature conversion? We already created a function that can do this for us in lesson 8 so what we want to do now is import it and use it in a new file.

Two hints:

  • If you have forgotten how to import modules, you can go back to the last lesson.
  • If you get some seemingly strange output, go back to the file you imported. If you print something in this file you imported, it will also be printed in your new file, thus adding some unforeseen output.


Your result may look like this:

Finally, you should also consider that Python does not re-read a file if you have already imported it. So if you make changes in a file and want to use it imported in another one, you have to restart the execution, i.e. just run the program again.

Like in some previous lessons, I recommend looking at Think Python by Allen B. Downey for more detailed information. It was also the inspiration for this post.

Congratulations! You have already completed 10 lessons! #mastery10

Leave a comment