Modules in Python are files that you can import to use in the file you're currently working in. Each module is a different file and you can import as many of them as you want and use the code that is available to you.
Python has many built-in modules, and we've already used one extensively in this class, namely the
Here are some other popular useful built-in modules that might be familiar to you:
To demonstrate modules, let's create a simple one and import it in another file. Again, modules are just normal Python files. Create a file named
circles.py and add this code:
import math def get_area_of_circle(radius): return radius * radius * math.pi
Now in an entirely different file, we can do something like this:
import circles area = circles.get_area_of_circle(5) print(area)
It is truly that simple. When you import a module, you are now free to use the variables and functions inside that file.
You don't necessarily need to import the entire thing. Let's say you only wanted a specific function inside the module. You can import just that function, like so:
from circles import get_area_of_circle area = get_area_of_circle(5) print(area)
The output is the same but now if
circles.py had multiple functions inside, you only imported the one you planned to use.
One last thing you can do when importing a module is giving it a new name if you want to. Here's how that looks:
import circles as c area = c.get_area_of_circle(5) print(area)
It's as simple as that! Maybe the original module name is too long, or maybe it conflicts with another module. Renaming is a good way to resolve that issue!