Python Module
Python Module
Python Modules
Python Module is a file that contains built-in functions,
classes,its and variables. There are many Python modules,
each with its specific work.
To create a Python module, write the desired code and save that in
a file with .py extension. Let’s understand it better with an example:
Example:
Let’s create a simple calc.py in which we define two functions,
one add and another subtract.
import calc
print(calc.add(10, 2))
Output:
12
Python Import From Module
Python’s from statement lets you import specific attributes from a module
without importing the module as a whole.
Here, we are importing specific sqrt and factorial attributes from the math
module.
Example:
# importing sqrt() and factorial from the module math
from math import sqrt, factorial
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
Note : if we simply do "import math", then
math.sqrt(16) and math.factorial() are required.
Import all Names
The * symbol used with the import statement is used to
import all the names from a module to a current
namespace.
Syntax:
from module_name import *
What does import * do in Python?
The use of * has its advantages and disadvantages. If you know exactly
what you will be needing from the module, it is not recommended to use
*, else do so.
Example
# importing sqrt() and factorial from the # module math
from math import *
print(sqrt(16))
print(factorial(6))
Output
4.0
720
Import Specific Functions with Alias in
Python
In Python, you can import a specific function or
class from a module and give it a custom name
(alias) using the as keyword.
This helps in:
• Making names shorter or more readable.
• Avoiding naming conflicts.
Syntax:
from module_name import function_name as alias_name
Example: Importing datetime module with an
Alias
from datetime import datetime as dt
# Get current date and time
now = dt.now()
print("Current Date and Time:", now)
print("Hour:", now.hour)
print("Minute:", now.minute)
Output:
Current Date and Time: 2025-05-01 14:23:45.123456
Hour: 14
Minute: 23
Problem Statement
1. Import Specific Functions with Alias
Use from datetime import datetime as dt to:
Print the current date and time.
Extract and print just the current hour and minute.