Python Docs

Python Creating Modules — Full Cheat Sheet

A Python module is simply a file that contains Python code — functions, variables, classes, or executable statements. It allows you to split your code into reusable pieces.

What is a Module?

Think of a module as a reusable code library that you can import into any Python program.

Creating a Module

To create a module, simply save your Python code into a file that ends with .py.

Example (save in mymodule.py):

def greeting(name):
  print("Hello, " + name)

Using a Module

You can import your module into any Python file using the import keyword.

import mymodule

mymodule.greeting("Jonathan")

When calling functions inside a module, use:
module_name.function_name

Modules Can Contain Variables

A module may contain variables such as numbers, lists, dictionaries, etc.

Example content of mymodule.py:

person1 = {
  "name": "John",
  "age": 36,
  "country": "Norway"
}

Accessing a variable inside the module:

import mymodule

a = mymodule.person1["age"]
print(a)

Why Use Modules?

  • Organizes large programs cleanly
  • Breaks code into manageable pieces
  • Allows reuse across multiple files or projects
  • Avoids rewriting the same functions again