-
Hajipur, Bihar, 844101
A module in Python is a file that contains Python code — like functions, classes, or variables — which can be used in other Python files.
Modules help you organize and reuse your code across projects.
Python has many built-in modules that you can import and use.
import math
print(math.sqrt(16)) # Output: 4.0
✅ You use the import
keyword to load a module.
There are different ways to import a module:
import random
print(random.randint(1, 10))
import datetime as dt
print(dt.datetime.now())
from math import pi
print(pi)
from math import *
print(sin(0))
✅ It's better to import only what you need.
Create a new file called mymodule.py
:
def greet(name):
print("Hello", name)
Then, use it in another file:
import mymodule
mymodule.greet("Alice")
When you import a module, Python searches in:
Current directory
Environment paths
Installed libraries
dir()
FunctionUse dir()
to list all the functions and attributes inside a module:
import math
print(dir(math))
math
— mathematical functions
random
— generate random numbers
datetime
— work with dates and times
os
— interact with the operating system
sys
— access system-specific parameters
Q1. Write a Python program to import the math
module and use the ceil()
function to round up a number.
Q2. Write a Python program to use random.choice()
to pick a random item from a list of your favorite fruits.
Q3. Write a Python program to import the datetime
module with an alias dt
and print the current date.
Q4. Write a Python program to create a module file calc.py
with an add()
function that adds two numbers.
Q5. Write a Python program to import add()
from the calc
module and use it in your main script.
Q6. Write a Python program to use from math import pi
and print the value of pi
.
Q7. Write a Python program to try importing a non-existing module and handle the ModuleNotFoundError
using try/except
.
Q8. Write a Python program to use the os
module to get and print the current working directory.
Q9. Write a Python program to use dir()
to list all attributes and functions of the datetime
module.
Q10. Write a Python program to call a function from your own custom module stored in a separate .py
file.
Q1: What is a module in Python?
Q2: Which keyword is used to include a module?
Q3: What does import math do?
Q4: How do you import a module with an alias?
Q5: What is the benefit of using modules?
Q6: What does dir() function return?
Q7: What file extension is used for a Python module?
Q8: Can you create your own modules in Python?
Q9: How to import only one function from a module?
Q10: What module lets you interact with the OS?