Python Modules

Python Modules Tutorial

A module in Python is a file containing Python code β€” functions, classes, and variables β€” that can be imported and reused in different programs. Modules help organize code, improve reusability, and keep things clean and modular! Let’s break it down.


🌟 1. Importing Modules

To use a module, we use the import keyword.

βœ… Import the entire module:

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

βœ… Import a specific function:

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

βœ… Import a module with an alias:

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

πŸ” 2. Built-in Python Modules

Python provides a rich set of standard libraries. Let’s look at some popular ones!

✨ Math Module (math)

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

✨ Random Module (random)

import random
print(random.randint(1, 10))  # Random number between 1 and 10
print(random.choice(['apple', 'banana', 'cherry']))  # Random choice

✨ Datetime Module (datetime)

import datetime
now = datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))  # Current date and time

πŸ§‘β€πŸ³ 3. Creating Your Own Python Module

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

βœ… mymodule.py

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

βœ… Using the custom module:

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

βœ… Ensure the .py file is in the same directory as your script.


🏷️ 4. Finding Installed Modules

You can see a list of installed modules with:

help("modules")

πŸ” 5. Packages (Multiple Modules)

A package is a collection of modules organized into directories with an __init__.py file.

βœ… Folder structure:

my_package/
β”‚
β”œβ”€β”€ __init__.py
β”œβ”€β”€ module1.py
β”œβ”€β”€ module2.py

βœ… Using the package:

from my_package import module1, module2

πŸš€ Conclusion

  • Modules help you write reusable, organized code.
  • Use built-in modules for common tasks and create custom ones for modular projects!
  • Once you master Python modules, you’re well on your way to building powerful, maintainable applications.

✨ Let me know if you’d like to dive deeper into a specific Python module! πŸš€

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