Module4 Notes 1
Module4 Notes 1
PYTHON PROGRAMMING
1BPLC105B/205B
Module-4
Modules: Random numbers, the time module, the math module, creating your own modules,
Namespaces,
Scope and lookup rules, Attributes and the dot Operator, Three import statement variants.
Mutable versus immutable and aliasing
Object oriented programming: Classes and Objects — The Basics, Attributes, Adding methods to
our class,
Instances as arguments and parameters, Converting an instance to a string, Instances as return
values.
Chapter: 8.1-8.8, 9.1, 11.1
A
reused in other Python programs. Python comes with many built-in modules as part of its standard library,
which help programmers perform common tasks easily. Examples of such modules are the turtle module (used
D
for graphics) and the string module (used for string operations). Python also provides a help system that allows
users to explore all available standard modules and understand how to use them.
AD
[Link] 1
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
[Link] 2
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
For example:
• In testing: fixed seed is desirable
U
• In games: fixed shuffling would make the game boring and predictable
VT
[Link] 3
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
[Link] 4
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
rng = [Link]()
VT
for i in range(num):
while True:
candidate = [Link](lower_bound, upper_bound)
if candidate not in result:
break
[Link](candidate)
return result
Example Output
xs = make_random_ints_no_dups(5, 1, 10000000)
print(xs)
# [3344629, 1735163, 9433892, 1081511, 4923270]
Why This Works
[Link] 5
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
A
Because it is impossible to generate more unique numbers than the range allows.
D
4.2 The time Module
AD
As programs become larger and algorithms more complex, an important question arises:
Is our code efficient?
One practical way to answer this is by measuring execution time—that is, how long a piece of code takes to
run. Python provides the time module for this purpose.
U
The [Link]() function returns a floating-point value representing the number of seconds elapsed since the
program started running.
Basic Timing Strategy
1. Call clock() before the code you want to measure → store in t0
2. Execute the code
3. Call clock() after execution → store in t1
4. Compute elapsed time as:
5. t1 − t0
This difference tells us how fast the code ran.
[Link] 6
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Test Setup
sz = 10000000 # 10 million elements
testdata = range(sz)
A
D
Timing the User-Defined Function
t0 = [Link]()
AD
my_result = do_my_sum(testdata)
t1 = [Link]()
U
Sample Output
my_result = 49999995000000 (time taken = 1.5567 seconds)
their_result = 49999995000000 (time taken = 0.9897 seconds)
[Link] 7
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Analysis of Results
• Both methods produce the same correct result
• The built-in sum() function is faster
• The user-defined function is approximately 57% slower
• Built-in functions are optimized at a lower level, making them more efficient
Despite this, summing 10 million numbers in under a second using the built-in function is very efficient.
Important Note (Modern Python)
In newer versions of Python, [Link]() is deprecated. Functions like:
• time.perf_counter()
• time.process_time()
[Link]
• Value of π (pi)
• Output: 3.141592653589793
U
math.e
VT
[Link] 8
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Radians vs Degrees
• Radians are the standard unit for angles in programming.
• Python provides:
A
D
o [Link]() → degrees to radians
AD
[Link] 9
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
s = "A string!"
seqtools.remove_at(4, s)
Output
U
'A sting!'
VT
[Link] 10
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
4.5 Namespaces
A namespace is a collection of identifiers (names) such as variables, functions, and objects that belong to a
module, function, or class. Namespaces help organize code and prevent name conflicts.
Generally, a namespace contains related items, for example:
• All mathematical functions in the math module
• All random-related functions in the random module
A
D
Why Namespaces Are Important
Namespaces allow:
AD
Each module has its own namespace, so identical names in different modules do not interfere with each other.
[Link] 11
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
print([Link])
print([Link])
print([Link])
print([Link])
Output
What is the meaning of Life, the Universe, and Everything?
What is your quest?
42
To seek the holy grail.
Explanation
• Both modules define question and answer
• No conflict occurs because:
o [Link] and [Link] exist in different namespaces
Function Namespaces
A
D
Functions also create their own namespaces.
AD
Example
def f():
n=7
U
def g():
n = 42
print("printing n inside of g:", n)
n = 11
print("printing n before calling f:", n)
f()
print("printing n after calling f:", n)
g()
print("printing n after calling g:", n)
Output
printing n before calling f: 11
printing n inside of f: 7
[Link] 12
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
[Link](4)
You are accessing sqrt inside the math namespace.
[Link] 13
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
2. Global Scope
• Identifiers declared at the top level of a module (file)
• Accessible throughout the module
• Shared by all functions in that module
3. Built-in Scope
• Identifiers provided by Python itself
• Examples: range, min, len, print
• Available without importing anything
[Link] 14
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Explanation
• Python finds range in the global scope
• This hides the built-in range
U
• Therefore, Python calls the user-defined function, not the built-in one Redefining built-in names like
range or min is bad practice and should be avoided because it causes confusion.
VT
[Link] 15
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
In Python, variables defined inside a module are called attributes of that module. Similarly, objects (such as
VT
[Link] 16
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
When a name includes the module (or object) it belongs to, it is called a fully qualified name.
Examples:
VT
• [Link]
• [Link]
• seqtools.remove_at
Using fully qualified names:
• Clearly specifies which attribute is being referred to
• Avoids ambiguity when multiple modules have attributes with the same name
[Link] 17
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
x = [Link](10)
Explanation
• Only the name math is added to the current namespace.
• Functions and constants inside the module must be accessed using dot notation.
• Example:
o [Link](10)
o [Link]
Advantages
• Clear and explicit
• Avoids name conflicts
• Easy to understand which module a function comes from
This is the preferred and safest method.
• The names cos, sin, and sqrt are imported directly into the current namespace.
• The module name math is not imported.
• Using [Link](10) will cause an error.
U
Advantages
VT
• Less typing
• Convenient when using a few functions frequently
Disadvantages
• Possible name clashes
• Less clear where a function originated
[Link] 18
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
x = [Link](10) # Error
Explanation
• math is imported inside the function
U
[Link] 19
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
my_list = [2, 4, 5, 3, 6, 1]
my_list[0] = 9
U
print(my_list)
VT
Output
[9, 4, 5, 3, 6, 1]
Here, the value at index 0 is successfully changed, proving that lists are mutable.
[Link] 20
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Result
TypeError: 'tuple' object does not support item assignment
This error occurs because tuples do not allow modification.
Aliasing
Aliasing occurs when two or more variables refer to the same object in memory. This is common with
mutable objects like lists.
Example: Aliasing with Lists
list_one = [1, 2, 3, 4, 6]
list_two = list_one
list_two[-1] = 5
print(list_one)
Output
[1, 2, 3, 4, 5]
Even though only list_two was modified, list_one also changed. This happens because both variables point to
the same list.
A
D
Memory Address Check Using id()
AD
True
VT
[Link] 21
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
list_two[-1] = 5
print(list_two)
print(list_one)
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 6]
Changes to one list do not affect the other.
A
To handle this properly, Python provides the copy module, which supports deep copying.
D
AD
[Link] 22
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Procedural Programming
• Focuses on functions or procedures
• Data and functions are separate
• Functions operate on external data
Example idea:
• Write functions
• Pass data to functions
• Data is not tightly bound to behavior
Object-Oriented Programming
• Focuses on objects
• An object contains:
o Data (attributes)
o Functionality (methods)
• Data and behavior are bundled together
This approach more closely models real-world systems.
A
D
AD
Real-World Analogy
In OOP:
• Each object represents a real-world entity or concept
• The data represents properties
• The functions (methods) represent actions
Example (conceptual):
• A car object:
[Link] 23
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
• x → horizontal position
• y → vertical position
Examples:
U
• (0, 0) → origin
VT
[Link] 24
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
def __init__(self):
""" Create a new point at the origin """
self.x = 0
self.y = 0
def __init__(self):
• Called the initializer
• Automatically runs whenever a new object is created
• Used to set initial values of attributes
4. The self Parameter
• Refers to the newly created object
• Used to create and access attributes
• self.x and self.y belong to the specific object being created
[Link] 25
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
[Link] 26
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
p.x = 3
p.y = 4
• Here, p refers to a Point object
• x and y are attributes of that object
• Their values are updated to 3 and 4
o y→4
• Each attribute refers to a numeric value
U
Understanding p.x
The expression:
[Link] 27
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
p.x
means:
“Go to the object that p refers to, and retrieve the value of its attribute x.”
There is no conflict between:
• x (a variable in the global namespace)
• p.x (an attribute in the object’s namespace)
The dot notation ensures unambiguous access.
• Calculation:
• 3² + 4² = 9 + 16 = 25
• Result:
U
• distance_squared_from_origin = 25
VT
[Link] 28
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
class Point:
""" Point class represents and manipulates x,y coords. """
def __init__(self, x=0, y=0):
""" Create a new point at x, y """
self.x = x
self.y = y
What Changed?
• The __init__ method now accepts two parameters: x and y
• Both parameters have default values of 0
• This allows us to:
o Create points at any location
o Still create the origin (0, 0) easily
r = Point() # origin
print(p.x, q.y, r.x)
Output
U
430
VT
Explanation
• p is created at (4, 2)
• q is created at (6, 3)
• r uses default values and represents (0, 0)
[Link] 29
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Strictly speaking:
• The __init__ method does not create the object
• The object is created first
• __init__ only initializes it with default or provided values
However:
• In practice, creation and initialization happen together
• Tools and editors show the __init__ docstring as help when calling the class constructor
• Therefore, the docstring is written to guide the user of the class, not to be technically pedantic
4.10.5 Adding Other Methods to Our Class
The real power of using a class (like Point) instead of a simple tuple (x, y) becomes clear when we start adding
methods. A class allows us to group data and the operations that make sense for that data in one place.
What Is a Method?
• A method is like a function
• It is defined inside a class
• It is called on an object (instance)
• It is accessed using dot notation
Example:
p.distance_from_origin()
This is similar in style to:
[Link] 30
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
[Link](90)
def distance_from_origin(self):
""" Compute my distance from the origin """
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
A
D
Using the Method
AD
Example 1
p = Point(3, 4)
p.distance_from_origin()
U
Output
VT
5.0
Example 2
q = Point(5, 12)
q.distance_from_origin()
Output
13.0
Example 3 (Origin)
r = Point()
r.distance_from_origin()
Output
[Link] 31
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
0.0
• Behaves independently
VT
[Link] 32
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Output
VT
(3, 4)
What Happens Internally
• p holds a reference to a Point object
• When p is passed to print_point, the parameter pt refers to the same object
• No new object is created
• This is why pt.x and pt.y correctly access the attributes of p
[Link] 33
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
[Link] 34
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
def __str__(self):
return "({0}, {1})".format(self.x, self.y)
Resulting Behavior
p = Point(3, 4)
str(p)
print(p)
Output
(3, 4)
A
D
(3, 4)
AD
Now:
• str(p) returns a meaningful string
• print(p) displays the same clean representation
U
VT
[Link] 35
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Output
(4.0, 8.0)
The returned value r is a Point instance, not a tuple or list.
U
VT
[Link] 36
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Function Method
midpoint(p, q) A
Defined inside a class
[Link](q)
D
Both approaches return new objects, but the method approach is more object-oriented.
AD
Composability of Calls
U
Object creation and method calls can be combined without assigning intermediate variables.
Example
VT
[Link] 37
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
[Link] 38
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
[Link] 39
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
An object’s state is stored in its attributes, and methods are used to:
• Read the state
• Modify the state
A
D
Example 2: Bank Account Object
AD
Possible Methods
• get_balance() → checks the current balance
• deposit(amount) → increases the balance
• withdraw(amount, description) → decreases the balance and records the transaction
• show_transactions() → displays the transaction history
Each method:
• Uses the existing state
• Updates the state appropriately
[Link] 40
1BPLC105B/205B PYTHON PROGRAMMING MODULE-04 AZ Document
Key Concept
• Attributes = state
• Methods = behavior
• Methods change or use the state of the object
• The object remains consistent and self-contained
Real-World Analogy
Just like real-world objects:
• A mobile phone has state (battery level, silent mode, network)
•
A
Actions like calling or switching to silent change the phone’s state
D
OOP mirrors this real-world behavior closely.
AD
U
VT
[Link] 41
Thank You
We’re glad to be part of your engineering journey.
Keep exploring, keep innovating, and keep growing.
AZ Documents
Your Engineering Study Partner
[Link]
A
D
Quality notes, simplified explanations, and
AD