Python Modules

Python Modules Tutorial

A module in Python is a file containing Python code (functions, classes, or variables) that can be imported and reused in different programs. Modules help organize code and improve reusability.


1. Importing Modules in Python

Python provides three ways to import a module:

1.1 Import the Entire Module

import math
print(math.sqrt(25))  # Output: 5.0

Access module functions using module_name.function_name().


1.2 Import a Specific Function from a Module

from math import sqrt
print(sqrt(36))  # Output: 6.0

No need to use math. prefix after importing a specific function.


1.3 Import a Module with an Alias (Short Name)

import math as m
print(m.pi)  # Output: 3.141592653589793

Using aliases makes code shorter and more readable.


2. Built-in Python Modules

Python includes many pre-installed modules, such as:


3. Using Built-in Python Modules

3.1 Math Module Example

import math
print(math.factorial(5))  # Output: 120
print(math.pow(2, 3))  # Output: 8.0

3.2 Random Module Example

import random
print(random.randint(1, 10))  # Output: Random number between 1 and 10
print(random.choice(["Apple", "Banana", "Cherry"]))  # Output: Random choice

3.3 Datetime Module Example

import datetime
current_time = datetime.datetime.now()
print(current_time)  # Output: Current date and time

4. Creating a Custom Python Module

You can create your own module by saving Python functions in a .py file.

4.1 Create a File Named mymodule.py

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

4.2 Import and Use the Custom Module

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

Ensure the module file (mymodule.py) is in the same directory as your script.


5. Finding Installed Modules

To see all available modules, run:

help("modules")

Conclusion

Python modules help organize code, improve reusability, and simplify complex programs. Using built-in and custom modules effectively can save time and reduce errors.

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment