If you find a bug in a program that is several months old, and you can’t understand the code enough to find or fix the bug, you have a big problem. The second most important part of programming, after making the code work, is making the code easy to understand. There will be several topics about ease-of-understanding tips and tricks, and our first installment will be about modules.
If this is your first time here, I recommend looking at the first lesson. Starting there and going through the rest of the lessons will prepare you to go through this more advanced lesson!
Oh, this topic is about modules? I guess I should start then.
module is a Python term for a file that contains Python code, or a .py file. The file we made last lesson (lesson_9.py) is a module. We can use the functions (
main) without redefining them by
importing the module!
>>> import lesson_9
We can now access the functions in our
lesson_9 module by using the format:
module.function(). Here’s our module and function:
>>> lesson_9.greet('Rhonin') Hello Rhonin! Nice to meet you!
This lets us keep our code organized by putting related code together in the same module without cluttering it up!
There are several built-in modules in Python. In fact, there are a whole library of them! I recommend looking there for all your module needs! Here’s a few examples:
1 2 3 4 5 6
>>> import random # For getting random numbers >>> import urllib # For accessing website urls >>> import tkinter # A GUI module >>> import sys # System functions >>> import os # Operating-System interface functions >>> import os.path # Functions for navigating the file system
Let me know in the comments if you want to see one of these modules! Each one can do some pretty cool stuff!