Modules in Python (Part-13)

What is a Module?

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added. Modules can define functions, classes, and variables, and can also include runnable code.

Example: Creating a Module

Create a file named mymodule.py with the following content:

# mymodule.py

def greeting(name):
    return f"Hello, {name}!"

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

Using a Module

To use the module, import it into another Python file or the interactive shell:

# main.py

import mymodule

print(mymodule.greeting("Alice"))  # Output: Hello, Alice!

print(mymodule.person1["name"])    # Output: John

Importing Specific Attributes

You can import specific functions, classes, or variables from a module:

# main.py

from mymodule import greeting, person1

print(greeting("Alice"))  # Output: Hello, Alice!
print(person1["age"])     # Output: 36

Renaming a Module

You can rename a module when importing it using the as keyword:

# main.py

import mymodule as mm

print(mm.greeting("Alice"))  # Output: Hello, Alice!
print(mm.person1["country"]) # Output: Norway

Built-in Modules

Python has several built-in modules that you can use without installing them. Examples include math, datetime, and random.

# Using built-in module

import math

print(math.sqrt(16))  # Output: 4.0

import datetime

now = datetime.datetime.now()
print(now)

Installing External Modules

You can install external modules using pip, the Python package manager. For example, to install the requests module:

pip install requests

After installation, you can import and use the requests module in your Python code:

import requests

response = requests.get("https://api.github.com")
print(response.status_code)

Summary

  • Modules: Files containing Python code (.py files) that define functions, classes, and variables.
  • Creating a Module: Write a .py file with your code.
  • Using a Module: Import the module into another Python file using the import statement.
  • Built-in Modules: Use standard modules included with Python.
  • External Modules: Install additional modules using pip

Creating a Module

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py added.

Let’s create a module named mymodule.py:

# mymodule.py

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

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

Using the Module

You can now use the module you’ve created by importing it into your script.

# main.py

import mymodule

mymodule.greeting("Jonathan")

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

Using as to Create an Alias

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

# main.py

import mymodule as mx

mx.greeting("Jonathan")

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

Importing Specific Parts of a Module

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

# main.py

from mymodule import greeting

greeting("Jonathan")

Importing All Functions from a Module

You can import all the functions from a module by using the * keyword.

# main.py

from mymodule import *

greeting("Jonathan")
print(person1["age"])

Built-in Modules

Python has a number of built-in modules that you can use right out of the box.

# main.py

import platform

x = platform.system()
print(x)

Creating an Alias for a Module

You can create an alias for a module to use in your script.

# main.py

import platform as pl

x = pl.system()
print(x)

Example of Using Built-in Math Module

# main.py

import math

x = math.sqrt(64)
print(x)

Related Posts

Package your Python code as Wheel File (Part-20)

Package your Python code as Wheel File If you want to share code with others or create libraries for your code so other can use your code….

Read More

map() function in Python (Part-19)

Using map() Function in Python The map() function in Python is used to apply a function to all the items in an input list. Here are some…

Read More

User Input | input() function |File Handling| open() function in Python (Part-18)

Using input() in Python 3.6 and later When you run this code, it will prompt you to enter a username and then print the entered username. Using…

Read More

Try…Except in Python | Exception handling in Python (part-17)

Exception Handling When an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using…

Read More

PIP in Python (Part-16)

What is PIP? PIP is a package manager for Python. It allows you to install and manage additional libraries and dependencies that are not included in the…

Read More

JSON in Python (Part-15)

JSON in Python JSON (JavaScript Object Notation) is a lightweight data interchange format that’s easy for humans to read and write, and easy for machines to parse…

Read More
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x