Hereβs a simple explanation of Modules in Python with examples, definitions, and practice questions
π§ What is a Module in Python?
- A module is a Python file (.py) that contains code, functions, or variables.
- You can import and use it in another file.
- Python has built-in modules and you can also create your own.
π Why Use Modules?
- To reuse code.
- To organize code in separate files.
- To keep programs clean and simple.
β Types of Modules
Type | Example |
---|---|
Built-in | math , random , datetime |
User-defined | Your own file like myfile.py |
External (3rd party) | numpy , pandas (need to install) |
β Importing a Module
π Syntax:
import module_name
πΉ Example:
import math
print(math.sqrt(16)) # Output: 4.0
β Using Specific Functions from a Module
from math import sqrt, pi
print(sqrt(25)) # Output: 5.0
print(pi) # Output: 3.1415926535...
β Rename a Module (alias)
import math as m
print(m.pow(2, 3)) # Output: 8.0
β Creating Your Own Module
Step 1: Create a file called mymodule.py
# mymodule.py
def greet(name):
print("Hello", name)
def add(a, b):
return a + b
Step 2: Use it in another file:
# main.py
import mymodule
mymodule.greet("Ravi")
print(mymodule.add(5, 3)) # Output: 8
β Built-in Module Examples
πΉ math
Module
import math
print(math.ceil(4.2)) # Output: 5
print(math.floor(4.7)) # Output: 4
print(math.factorial(5)) # Output: 120
πΉ random
Module
import random
print(random.randint(1, 10)) # Random number from 1 to 10
πΉ datetime
Module
import datetime
now = datetime.datetime.now()
print(now) # Current date and time
π Practice Questions + Answers
β Q1: Import math
module and print the square root of 81.
β Answer:
import math
print(math.sqrt(81)) # Output: 9.0
β Q2: Create your own module with a function that says “Welcome!” and call it.
β Answer:
File: mygreet.py
def welcome():
print("Welcome to Python!")
File: main.py
import mygreet
mygreet.welcome()
β Q3: Use the random
module to print a random number between 50 and 100.
β Answer:
import random
print(random.randint(50, 100))
β Q4: From math
module, import only pow
and sqrt
.
β Answer:
from math import pow, sqrt
print(pow(2, 3)) # 8.0
print(sqrt(49)) # 7.0
β Q5: What is the benefit of using modules?
β Simple Answer:
- Reuse code
- Organize code
- Avoid writing the same code again
π Summary Table
Concept | Example |
---|---|
import | import math |
from | from math import sqrt |
as | import math as m |
User Module | import mymodule |
External Module | Install with pip install |
Leave a Reply