1) What is a Module in Python?
— Explanation
A module in Python is simply a file that contains Python code — like functions, variables, and classes —
that you can reuse in other programs.
Think of it as a toolbox:
Each module is a toolbox.
Each function or variable inside it is a tool you can use anytime without rewriting it.
Examples of built-in modules:
math, random, datetime, os, sys, json, etc.
Example of a user-defined module:
A .py file that you create containing your own reusable code.
2) How to Use and Create Modules
(a) Using Built-in Modules
You use the import keyword.
import math
print([Link](25)) # using math module function
print([Link]) # accessing constant
Or import specific parts:
from math import sqrt, pi
print(sqrt(16))
print(pi)
Or give a short name (alias):
import math as m
print([Link](2, 3))
(b) Creating Your Own Module
1. Create a new file named [Link]
2. Write some functions or variables inside it:
[Link]
def greet(name):
print("Hello,", name)
def add(a, b):
return a + b
pi_value = 3.1415
3. Now create another Python file and import your module:
[Link]
import myModule
[Link]("Akash")
print("Sum:", [Link](10, 5))
print("Pi value:", myModule.pi_value)
Output:
Hello, Akash
Sum: 15
Pi value: 3.1415
This is how you can reuse your own code anywhere.
3) The random Module — Practice and Examples
The random module is used to generate random numbers or select random items.
It’s very useful for games, simulations, and data sampling.
Let’s look at common and useful functions.
Example 1: Generate random numbers
import random
print([Link](1, 10)) # Random integer between 1 and 10
print([Link]()) # Random float between 0.0 and 1.0
print([Link](1, 5)) # Random float between 1 and 5
Example 2: Choose random elements from a list
import random
colors = ['red', 'green', 'blue', 'yellow']
print([Link](colors)) # Pick one random element
print([Link](colors, 2)) # Pick 2 unique random elements
[Link](colors) # Shuffle the list
print(colors)
Example 3: Simulate a dice roll
import random
dice = [Link](1, 6)
print("You rolled a:", dice)
Example 4: Generate random passwords
import random
import string
characters = string.ascii_letters + [Link] + [Link]
password = ''.join([Link](characters) for i in range(10))
print("Generated Password:", password)
Practice Ideas
1. Create your own module named [Link] with functions: square, cube, and average.
2. Import it in another file and test it.
3. Use the random module to:
o Roll two dice and show their sum.
o Select a random student from a list.
o Generate a random OTP (6-digit number).