MODULE - 4
1. Random Numbers Module
The random module provides functions for generating random numbers.
--Specific applications of the random module
Game development:
Simulation and modeling:
Machine learning:
Splitting datasets for training and testing models.
Security and authentication:
Generating one-time passwords, tokens, and random passwords for user accounts.
Testing and debugging:
Creating random test data for algorithms.
import random
# Random float between 0.0 and 1.0
print("random():", [Link]())
# Random integer in range [1, 6] (inclusive)
dice_roll = [Link](1, 6)
print("Dice roll:", dice_roll)
# Random choice from a list
colors = ['red', 'green', 'blue', 'yellow']
print("Random color:", [Link](colors))
# Random float in range [10, 20]
print("Random float:", [Link](10, 20))
# Output: Random float: 15.234567891234
# Shuffle a list (modifies in place)
cards = [1, 2, 3, 4, 5]
[Link](cards)
print("Shuffled cards:", cards)
# Random sample (without replacement)
lottery = [Link](range(1, 50), 6)
print("Lottery numbers:", lottery)
2. Time Module
The time module provides time-related functions.
import time
# Get current time in seconds since epoch (Jan 1, 1970)
current_time = [Link]()
print("Current timestamp:", current_time)
# Output: Current timestamp: 1733097600.123456
# Sleep for 2 seconds
print("Sleeping for 2 seconds...")
[Link](2)
print("Awake!")
# Get readable time
print("Readable time:", [Link]())
# Measure execution time
start = [Link]()
total = sum(range(1000000))
end = [Link]()
print(f"Calculation took {end - start:.4f} seconds")
# Output: Calculation took 0.0234 seconds
# Structured time
local_time = [Link]()
print("Year:", local_time.tm_year)
print("Month:", local_time.tm_mon)
print("Day:", local_time.tm_mday)
# Output: Year: 2025
# Output: Month: 12
# Output: Day: 1
3. Math Module
The math module provides mathematical functions.
import math
# Constants
print("Pi:", [Link])
# Output: Pi: 3.141592653589793
print("Euler's number:", math.e)
# Output: Euler's number: 2.718281828459045
# Trigonometric functions (angles in radians)
angle = [Link] / 4 # 45 degrees
print("sin(45°):", [Link](angle))
# Output: sin(45°): 0.7071067811865476
print("cos(45°):", [Link](angle))
# Output: cos(45°): 0.7071067811865476
# Convert degrees to radians
print("90° in radians:", [Link](90))
# Output: 90° in radians: 1.5707963267948966
# Logarithms
print("log(10):", [Link](10))
# Output: log(10): 2.302585092994046
print("log10(100):", math.log10(100))
# Output: log10(100): 2.0
# Power and roots
print("2^8:", [Link](2, 8))
# Output: 2^8: 256.0
print("√16:", [Link](16))
# Output: √16: 4.0
# Rounding functions
print("ceil(4.3):", [Link](4.3))
# Output: ceil(4.3): 5
print("floor(4.9):", [Link](4.9))
# Output: floor(4.9): 4
# Factorial
print("5!:", [Link](5))
# Output: 5!: 120
# Absolute value
print("fabs(-7.5):", [Link](-7.5))
# Output: fabs(-7.5): 7.5
Namespaces in Python – With Examples
A namespace in Python is a container that holds names (identifiers) and their corresponding
objects.
Examples of namespaces: Built-in, Global, Local, Enclosed.
Types of Namespaces
1. Local Namespace Example
Created inside a function.
def my_function():
x = 10 # local variable
print("Inside function:", x)
my_function()
print(x) # ERROR: x is not defined in global namespace
Note: x belongs to local namespace of my_function().
2. Global Namespace Example
Variables defined outside functions.
x = 50 # global variable
def show():
print("Inside function:", x)
show()
print("Outside function:", x)
Note: x belongs to global namespace, accessible inside functions.
3. Enclosed Namespace Example
Function inside a function.
def outer():
x = "outer value" # enclosed variable
def inner():
print(x) # inner function can access outer namespace
inner()
outer()
Note: x belongs to enclosed namespace of outer().
4. Built-in Namespace Example
Names provided by Python.
print(len("Hello")) # len() is from built-in namespace
Note: len, print, range etc. are from built-in namespace.
Demonstrates LEGB rule.
X = “global”
def outer():
x = “enclosed”
def inner():
x = “local”
print(x)
inner()
outer()
print(x)
Output:
local
global
Note: Inner picks local
Outside picks global
Scope and Lookup Rules (LEGB Rule)
Python follows LEGB order to find variables:
Local (L) – inside the current function
Enclosing € – outer functions (only in nested functions)
Global (G) – module-level variables
Built-in (B) – Python built-ins (len, print…)
Example
x = “global”
def outer():
x = “enclosing”
def inner():
x = “local”
print(x) # Prints local
inner()
outer()
- Attributes and the Dot Operator
Objects in Python have attributes (variables & methods).
The dot operator (.) is used to access them.
Examples
Accessing module attributes:
import math
print([Link])
print([Link](16))
- Three Import Statement Variants
Python provides three main importing styles:
1. import module
Syntax:
import math
import time
Usage:
[Link](25)
[Link]
2. from module import name
Syntax:
from math import sqrt, pi, cos, sin
Usage:
sqrt(25)
print(pi)
3.
from module import *
Syntax:
from math import *
1️ Mutability
Mutable objects → can be changed after creation.
Examples: Lists, Dictionaries, Sets.
You can modify values using indexing or methods.
Example:
my_list = [2, 4, 5, 3, 6, 1]
my_list[0] = 9
# Result: [9, 4, 5, 3, 6, 1]
2️ Immutability
Immutable objects → cannot be changed once created.
Examples: Strings, Tuples, Integers, Floats.
Example:
my_tuple = (2, 5, 3, 1)
my_tuple[0] = 9 # ❌ Error
Reason: Tuple does NOT support item assignment.
3️ Aliasing
Aliasing occurs when two variables refer to the same
object in memory.
List_one = [1, 2, 3, 4, 6]
list_two = list_one
list_two[-1] = 5
Result:
list_one → [1, 2, 3, 4, 5]
Why?
Note:
Both variables refer to the same memory address.
You can verify using id():
id(list_one) == id(list_two) # True
4️ Avoiding Aliasing (Copying Lists)
Shallow Copy
Copy using slicing:
list_two = list_one[:]
Now:
id(list_one) == id(list_two) # False
Changing one will not affect the other.
Limitation of Shallow Copy
It fails with nested lists:
a = [[1, 2], [3, 4]]
b = a[:] # shallow copy
b[0][1] = 99
# Both a and b change!
Reason: The inner lists are still shared.
5️ Deep Copy (For Nested Lists)
To fully separate the objects, use:
import copy
deep_list = [Link](a)
Deep copy creates a new independent copy, including all nested structures.
Summary
Mutable objects can be changed:
lists, dictionaries, sets.
Immutable objects cannot be changed:
tuples, strings, numbers.
Aliasing occurs when two variables point to the
same memory location, so a change via one variable
also changes the other.
Object oriented programming:
1. Classes and Objects – The Basics
-Object-Oriented Programming (OOP) is a programming paradigm that organizes software design
around classes and objects.
-A class is a usEr-defined blueprint that represents a group of objects having common properties
and behaviors.
-It contains attributes (data) and methods (functions).
-An object is an instance of a class. It represents real-world entities and occupies memory.
Example:
class Student:
def __init__(self, name, usn):
[Link] = name
[Link] = usn
s1 = Student("Kiran", "CS001")
Advantages:
Code reusability
Better data security
Easy maintenance
2. Attributes in Python Class
Attributes are variables that store data of an object.
Types of Attributes:
1. Instance Attributes
Defined inside __init__().
Different for each object.
2. Class Attributes
Defined inside the class but outside methods.
Shared by all objects.
Example:
class Student:
college = "BITM" # class attribute
def __init__(self, name):
[Link] = name # instance attribute
Importance:
Store object data
Help in data encapsulation
3. Adding Methods to a Class:
A method is a function defined inside a class and is used
to define the behavior of objects.
Types of Methods:
1. Instance methods
2. Class methods
3. Static methods
1. Example of Instance Method:
class Student:
def display(self):
print("This is a student class")
Key points:
First parameter is always self.
Methods operate on object data.
4. Instances as Arguments and Parameters
In Python, objects (instances) can be passed as
arguments to methods or functions.
This allows interaction between objects.
Example:
class Student:
def compare(self, other):
print("Comparing two students")
s1 = Student()
s2 = Student()
[Link](s2)
Advantages:
-Code reusability
-Supports object communication
5. Converting an Instance to a String
Python provides the special method __str__() to return
a human-readable string representation of an object.
Syntax:
class Student:
def __init__(self, name):
[Link] = name
def __str__(self):
return "Student Name: " + [Link]
NOTE:
When the object is printed using print(object),
the __str__() method is called automatically.
Advantages:
-Improves program readability
-Useful for debugging
6. Instances as Return Values
In Python, a function or method can return an object
(instance of a class).
This technique is useful in:
-Encapsulation of object creation
Example:
class Student:
def __init__(self, name):
[Link] = name
def create_student():
return Student("Ravi")
s1 = create_student()
print([Link])
Benefits:
Helps in object creation control
Encourages modular programming