CodeCraft Innovation
Software development expertise, coding education, ethical hacking focus, and IT advice services.
Let’s now understand the next useful concept in the Python Learning Series
*Modules and Packages*
These help you organize your code better and reuse it efficiently.
*1. What is a Module?*
A module is simply a .py file that contains Python definitions, functions, classes, or variables.
For example, if you have a file named math_utils.py:
def add(a, b):
return a + b
You can use it in another file like this:
import math_utils
print(math_utils.add(2, 3)) # Output: 5
You can also import specific parts:
from math_utils import add
print(add(2, 3))
*2. What is a Package?*
A package is a directory containing multiple related Python modules and an __init__.py file. This helps structure large projects.
*Example folder structure:*
myproject/
│
├── math_utils/
│ ├── __init__.py
│ └── operations.py
Then you can import like this:
from math_utils.operations import add
*3. Standard Modules You Should Know*
Python comes with many built-in modules. Here are a few:
math → Math operations
random → Generate random numbers
datetime → Work with dates and times
os → Interact with the operating system
sys → Access system-specific parameters
json → Handle JSON data
You can also install external modules using pip:
pip install requests
And then use it in your code:
import requests
response = requests.get('https://example.com')
This is an essential skill when your projects start growing. And you'll definitely use modules when working with APIs, web scraping, automation, or any real-world project.
Example Domain This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.
Let's now move to the next topic in the Python Learning Series:
*map(), filter(), and reduce() in Python*
These three functions are part of functional programming in Python and are often used for concise, clean, and readable code when working with lists or other iterable data.
*1. map(function, iterable)*
Applies a function to every item in the iterable.
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 2, nums))
print(squares) # Output: [1, 4, 9, 16]
*2. filter(function, iterable)*
Returns only the items that evaluate to True from the iterable based on the function.
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # Output: [2, 4, 6]
*3. reduce(function, iterable)*
Applies a function cumulatively to the items of the iterable.
*Note: You must import it from functools.*
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # Output: 24
These are powerful tools when used right. You'll see them often in interview questions and real-world code!
Click here to claim your Sponsored Listing.
Category
Telephone
Website
Address
Blantyre