🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Python Notes
Topic #91

Python Modules


What is a Module?

Consider a module to be the same as a code library.

A file containing a set of functions you want to include in your application.


Create a Module

To create a module just save the code you want in a file with the file extension .py:

Example

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

Use a Module

Now we can use the module we just created, by using the import statement:

Example

  import mymodule

mymodule.greeting("Jonathan")

Note: When using a function from a module, use the syntax: module_name.function_name.


Variables in Module

The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):

Example

person1 = {
  "name": "John",
  "age": 36,

"country": "Norway"
}

Example

  import mymodule

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

Naming a Module

You can name the module file whatever you like, but it must have the file extension .py

Re-naming a Module

You can create an alias when you import a module, by using the as keyword:

Example

  import mymodule as mx

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

Built-in Modules

There are several built-in modules in Python, which you can import whenever you like.

Example

  import platform

x = platform.system()
print(x)

Using the dir() Function

There is a built-in function to list all the function names (or variable names) in a module. The dir() function:

Example

  import platform

x = dir(platform)
print(x)

Note: The dir() function can be used on all modules, also the ones you create yourself.


Import From Module

You can choose to import only parts from a module, by using the from keyword.

Example

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

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

Example

  from mymodule import person1

print (person1["age"])

Note: When importing using the from keyword, do not use the module name when referring to elements in the module. Example: person1["age"], not mymodule.person1["age"]

Want to go beyond the notes?

Join CodingNow 2.0's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Python Modules – FAQs

Quick answers about learning Python Modules in Python.

This free note from CodingNow 2.0 explains Python Modules in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on CodingNow 2.0, including Python Modules, is 100% free with no signup required.
With focused practice, most students grasp Python Modules in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now