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.

Modules are like Amazon packages, but for your code!

Built-in Modules

Python has many built-in modules, and we've already used one extensively in this class, namely the math module.

Here are some other popular useful built-in modules that might be familiar to you:

  • array
  • copy
  • email
  • fileinput
  • gc
  • gzip
  • html
  • http
  • io
  • ipaddress
  • json
  • keyword
  • numbers
  • pip
  • pipes
  • random
  • ssl
  • statistics
  • string
  • symbol
  • sys
  • threading
  • time
  • token

Creating a Module

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 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.

Importing Module Objects

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 had multiple functions inside, you only imported the one you planned to use.

Renaming an Imported Module

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!


Next Lesson »
Copyright © 2017 - 2024 All rights reserved. Made with ❤ in NY.