Modules in Python

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

TypeExample
Built-inmath, random, datetime
User-definedYour 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

ConceptExample
importimport math
fromfrom math import sqrt
asimport math as m
User Moduleimport mymodule
External ModuleInstall with pip install

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *