0% found this document useful (0 votes)
2 views38 pages

Module3,4,5 Notes

The document outlines various programming tasks and concepts related to NumPy, file handling, modules, and object-oriented programming in Python. It includes explanations of slicing, masking, broadcasting, data types, and file operations, along with example programs for each concept. Additionally, it covers namespaces, variable lookup rules, and the creation of user-defined modules, emphasizing the importance of code organization and reusability.

Uploaded by

rsamarth619
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views38 pages

Module3,4,5 Notes

The document outlines various programming tasks and concepts related to NumPy, file handling, modules, and object-oriented programming in Python. It includes explanations of slicing, masking, broadcasting, data types, and file operations, along with example programs for each concept. Additionally, it covers namespaces, variable lookup rules, and the creation of user-defined modules, emphasizing the importance of code organization and reusability.

Uploaded by

rsamarth619
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE 3 NUMPY and FILES

1.​ Explain Slicing and Masking with an example.


2.​ Given the NumPy array [230, 210, 284, 89, 716], write a program that replaces every
element greater than 200 with 0 and stores the result in a new array.
3.​ What is Broadcasting in NumPy. Develop a program to illustrate Broadcasting array
elements.(Dec2025/ Jan 2026)
4.​ What is Masking in NumPy. Develop a program to illustrate masking to filter array
elements. (Dec2025/ Jan 2026)
5.​ What is the difference between: uint8, int8, uint16. Explain their ranges.
6.​ Create an array with value 200 using uint8 and uint16, adds the array to itself and
prints the result.
7.​ Develop a Python program to count the number of lines and words in the file
(Dec2025/ Jan 2026)
8.​ Develop a Python program to sort the contents of a text file in reverse order and write
the sorted contents into a separate file. (Dec2025/ Jan 2026)
9.​ Develop a program to sort the contents of a text file and write the sorted contents into
a separate text file.
10.​Write a Python program that creates a file named [Link]. The program should
write the following lines into the file:
●​ "Python is fun"
●​ "I am learning file handling"
●​ "End of file"

After writing to the file, read the contents of the file and print them on the console.

11.​Write a Python program that reads the entire contents of the file at once into a
string, and then counts the number of words and print the total number of words
12.​Illustrate the concept of Directories in the file system with an example program.
Module 4 MODULES and OOPS

1.​ Write a Python program to create a random number generator object, generate a
random integer between 1 and 100 and print the dice value.
2.​ Write a Python program that imports the math module and prints: the value of pi, the
value of e, the square root of 25.
3.​ Discuss the various methods of importing modules in python programs. (Dec2025/ Jan
2026)
4.​ Explain how to create user-defined modules in Python with an example. Also discuss
the uses of user defined modules. (Dec2025/ Jan 2026)
5.​ What is a namespace in Python? Write a Python program with: one global variable
named x, two functions, each having its own local variable named x. Print the values
to show how namespaces work.
6.​ Develop a Python program to illustrate how variable lookup follows LEGB (Local,
Enclosing, Global, Built-in) rule. (Dec2025/ Jan 2026)
7.​ Write a Python program that randomly selects 5 different months from a list of all 12
months without duplicates.
8.​ Explain Mutable versus immutable and aliasing with examples.
9.​ Develop a program that simulates a simple stopwatch that records random time
intervals and calculates the average elapsed time. (Dec2025/ Jan 2026)
10.​What is the purpose of the __init__() and __str__() method in Python classes?
(Dec2025/ Jan 2026)
11.​Write a method halfway() in the Point class that returns the midpoint between two
points. Use the points:(3, 4) and (5, 12) and display the midpoint.
12.​What is the purpose of the self parameter in Python classes?
13.​Define a function that takes TWO objects representing complex numbers and returns
a new complex number with the sum of two complex numbers. Define a suitable class
‘Complex’ to represent the complex number. Develop a program to read N (N >=2)
complex numbers and to compute the addition of N complex numbers.
14.​Define class and object. Explain with syntax and an example how to define a class in
python. How to initiate a class and how the class members are accessed (Dec2025/
Jan 2026)
Module 5 OOPS, INHERITANCE and EXCEPTIONS

1.​ Create a Python class Point with attributes x and y. Demonstrate sameness using 'is'
operator, deep equality using , and show the effect of mutability when modifying one
reference. (Dec2025/ Jan 2026)
2.​ Explain the term objects are mutable with an example. (Dec2025/ Jan 2026)
3.​ What is polymorphism? Develop a program to illustrate polymorphism by defining a
common interface method in two different classes. (Dec2025/ Jan 2026)
4.​ What is operator overloading? Define a Class Complex. Overload the + operator to
add two complex numbers. Write a Python program to read N (N2) complex numbers
and find their cumulative sum using operator overloading.
5.​ What is a modifier function? How is it different from a pure function?
6.​ Briefly explain Assertion and raise an exception. (Dec2025/ Jan 2026)
7.​ Explain the need for exception handling in Python. Develop a program to illustrate: try,
except, close, finally block and also show how to raise an exception. (Dec2025/ Jan
2026)
MODULE 3 NUMPY and FILES

Q1: Explain Slicing and Masking with an Example

Solution:
[Link]: Slicing is a technique used in NumPy to extract a portion of elements from an array. It
allows accessing specific elements using index positions.

Syntax: array [start : stop : step]

Examples

Example Program for Slicing:


2. Masking: Masking is a method used to filter array elements based on conditions. It returns
only the elements that satisfy the given condition.

Examples:

Example Program for Masking:

Q2. Given the NumPy array [230, 210, 284, 89, 716], write a program that replaces every
element greater than 200 with 0 and stores the result in a new array.
Solution:
NumPy arrays can be modified using conditional statements and loops. In this program, each
element is checked one by one. If the element is greater than 200, it is replaced with 0 and
stored in a new array.

Q3. What is Broadcasting in NumPy? Develop a Program to Illustrate Broadcasting


Array Elements.

Solution: Broadcasting is a feature in NumPy that allows arithmetic operations on arrays of


different shapes or sizes. It automatically expands the smaller array or scalar value to match the
shape of the larger array. Broadcasting reduces the need for loops and makes calculations
faster and easier.

Advantages

Reduces code complexity, Improves performance, Performs operations efficiently

Example program on broadcasting:


Q4. What is masking in NumPy? Develop a program to illustrate masking to filter array
elements.

Solution:
Masking in NumPy refers to selecting or filtering elements of an array using Boolean conditions.

A mask is simply a Boolean array (True/False) that has the same shape as the original array.

Where the mask is True, the element is selected; where it is False, the element is ignored.

Q5. Differentiate between uint8, int8 and uint16 with an Example.

Solution:
In NumPy, different data types are used to store integers with different memory sizes and
ranges.
uint8 stores only positive integers.
int8 stores both positive and negative integers.
uint 16 stores larger positive integers
uint8 → Unsigned 8-bit integer
size → 1byte
Range → 0 to 255
int8 → Signed 8-bit integer
size → 1 byte
Range → -128 to 127
uint16 → Unsigned 16-bit integer
size → 2 bytes
Range → 0 to 65535

Q6. Create an array with value 200 using uint8 and uint16, adds the array to itself and
prints the result.

Solution:

Q7. Develop a Python program to count the number of lines and words in the file
(Dec2025/ Jan 2026)

Solution:
Q8. Develop a Python program to sort the contents of a text file in reverse order and
write the sorted contents into a separate file. (Dec2025/ Jan 2026)

Solution:
Q9. Develop a program to sort the contents of a text file and write the sorted contents
into a separate text file.

Solution:

Q10. Write a Python program that creates a file named [Link]. The program should
write the following lines into the file:

●​ "Python is fun"
●​ "I am learning file handling"
●​ "End of file"

After writing to the file, read the contents of the file and print them on the
console.

Solution:
[Link]:
Python is fun
I am learning file handling
End of file

Q11. Write a Python program that reads the entire contents of the file at once into
a string, and then counts the number of words and print the total number of
words

Solution:

Q12. Illustrate the concept of Directories in the file system with an example
program.

Solution:
A directory is like a folder in a computer which is used to store files and other folders. It
helps us to organize data properly so that we can easily find and manage [Link] a file
system, directories are arranged in a tree structure. The main directory is called the root
directory. Inside it, there can be many subdirectories and files.
Module 4 MODULES and OOPS

Q1. Write a Python program to create a random number generator object, generate a
random integer between 1 and 100 and print the dice value.

Solution:

Q2. Write a Python program that imports the math module and prints: the value of pi,
the value of e, the square root of 25.

Solution:

Q3. Discuss the various methods of importing modules in python programs. (Dec2025/
Jan 2026)
Solution:
Method 1: Here just the single identifier math is added to the current namespace. If you want to
access one of the functions in the module, you need to use the dot notation to get to it as shown

Method 2: The names are added directly to the current namespace, and can be used without
qualification. The name math is not itself imported, so trying to use the qualified form [Link]
would give an error.

Method 3: make things shorter by importing a module under a different name as shown

Q4. Explain how to create user-defined modules in Python with an example. Also
discuss the uses of user defined modules. (Dec2025/ Jan 2026)

Solution:
A module in Python is a file containing Python definitions, functions, classes, and variables that
can be reused in other programs. A user-defined module is a module created by the
programmer to organize code and improve reusability.
Steps to Create a User-Defined Module
Step 1: Create a Module File
Create a Python file named [Link].
# [Link]
def add(a, b):
return a + b
def subtract(a, b):
return a – b
This file contains two functions: add() and subtract().
Step 2: Import the Module in Another Program
Create another file named [Link].
# [Link]
import mymodule
x = [Link](10, 5)
y = [Link](10, 5)
print("Addition =", x)
print("Subtraction =", y)
output:
Addition = 15
Subtraction = 5

Uses of User-Defined Modules


1.​ Code Reusability: Functions can be reused in multiple programs without rewriting code.
2.​ Better Code Organization: Large programs can be divided into smaller and manageable
files.
3.​ Easy Maintenance: Changes made in a module automatically reflect wherever the
module is used.
4.​ Improved Readability: Modular programming makes the code easier to understand.
5.​ Reduced Development Time: Frequently used functions can be stored and reused.
6.​ Supports Team Development: Different developers can work on different modules
independently.
7.​ Avoids Code Duplication: Common functionalities can be stored in a single module.
8.​ Encapsulation of Functionality: Related functions and variables can be grouped together.

Q5. What is a namespace in Python? Write a Python program with: one global variable
named x, two functions, each having its own local variable named x. Print the values
to show how namespaces work.
Solution:
A namespace in Python is a container that stores the mapping between variable names and
their corresponding objects. It helps avoid naming conflicts by keeping variables in different
scopes separate.

Python mainly has the following namespaces:

1.​ Built-in Namespace – Contains predefined functions and exceptions.

2.​ Global Namespace – Contains variables defined at the program level.

3.​ Local Namespace – Contains variables defined inside a function.


When a variable is referenced, Python searches namespaces in the order:​
Local → Global → Built-in (LGB Rule).

Program to Demonstrate Namespaces

# Global variable​
x = "Global x"​
def function1():​
x = "Local x in function1"​
print("Inside function1:", x)​
def function2():​
x = "Local x in function2"​
print("Inside function2:", x)​
# Function calls​
function1()​
function2()​
# Accessing global variable​
print("Outside functions:", x)

Output

Inside function1: Local x in function1​


Inside function2: Local x in function2​
Outside functions: Global x

Explanation
Global Namespace
x = "Global x"
●​ Variable x is defined outside all functions.
●​ It belongs to the global namespace and can be accessed throughout the program.
Local Namespace of function1()
x = "Local x in function1"
●​ This variable exists only within function1().
●​ It hides the global variable inside the function.
Local Namespace of function2()
x = "Local x in function2"
●​ This variable exists only within function2().
●​ It is independent of both the global variable and the local variable in function1().

Q6. Develop a Python program to illustrate how variable lookup follows LEGB (Local,
Enclosing, Global, Built-in) rule. (Dec2025/ Jan 2026)

Solution:
LEGB is the rule followed by Python to resolve variable names. When a variable is referenced,
Python searches for it in the following order:
1.​ L – Local Scope: Variables defined inside the current function.
2.​ E – Enclosing Scope: Variables in the enclosing (outer) function.
3.​ G – Global Scope: Variables defined at the module/program level.
4.​ B – Built-in Scope: Predefined names available in Python.
Python stops searching as soon as it finds the variable in one of these scopes.

Python Program
# Global variable​
x = "Global Variable"​
def outer():​
x = "Enclosing Variable"​
def inner():​
x = "Local Variable"​
print("Inside inner():", x) # Local Scope​
inner()​
print("Inside outer():", x) # Enclosing Scope​
outer()​
print("Outside functions:", x) # Global Scope​
# Built-in Scope​
print("Length of 'Python' =", len("Python"))
Output

Inside inner(): Local Variable​


Inside outer(): Enclosing Variable​
Outside functions: Global Variable​
Length of 'Python' = 6

Explanation
1. Local Scope (L)
x = "Local Variable"
●​ Defined inside inner().
●​ Python first searches in the local scope.
●​ Hence, inner() prints Local Variable.
2. Enclosing Scope (E)
x = "Enclosing Variable"
●​ Defined inside outer().
●​ Accessible to nested functions.
●​ After inner() completes, outer() prints Enclosing Variable.
3. Global Scope (G)
x = "Global Variable"
●​ Defined outside all functions.
●​ Accessible throughout the program.
●​ Printed outside the functions.
4. Built-in Scope (B)
len("Python")
●​ len() is a built-in Python function.
●​ Python finds it in the built-in namespace.

Q7. Write a Python program that randomly selects 5 different months from a list of all
12 months without duplicates.

Solution:

import random​
# List of all 12 months​
months = ["January", "February", "March", "April",​
"May", "June", "July", "August",​
"September", "October", "November", "December"]​
# Randomly select 5 different months​
selected_months = [Link](months, 5)​
print("Randomly Selected Months:")​
for month in selected_months:​
print(month)

Sample Output
Randomly Selected Months:​
March​
July​
December​
January​
September

(Output may vary each time the program is executed.)

Q8. Explain Mutable versus immutable and aliasing with examples.

Solution:
Ans : In Python, objects are classified as mutable or immutable based on whether their contents
can be changed after creation. Understanding mutability and aliasing is important for effective
memory management and avoiding unexpected program behavior.
1. Mutable Objects
A mutable object can be modified after it is created without changing its identity.
Examples of Mutable Data Types
●​ List
●​ Dictionary
●​ Set
Program Example
# Mutable object (List)​
list1 = [10, 20, 30]​
print("Before modification:", list1)​
list1[1] = 50​
print("After modification:", list1)
Output
Before modification: [10, 20, 30]​
After modification: [10, 50, 30]
Explanation
●​ The list object remains the same.
●​ Only its contents are modified.
2. Immutable Objects
An immutable object cannot be modified after it is created. Any modification creates a new
object.
Examples of Immutable Data Types
●​ Integer
●​ Float
●​ String
●​ Tuple
Program Example
# Immutable object (String)​
s = "Python"​
print("Original String:", s)​
s = s + " Programming"​
print("Modified String:", s)
Output
Original String: Python​
Modified String: Python Programming
Explanation
●​ Strings are immutable.
●​ A new string object is created instead of modifying the original one.

Difference Between Mutable and Immutable Objects


Mutable Objects Immutable Objects
Can be modified after creation Cannot be modified after creation
Memory location remains same New object is created on modification
Examples: List, Dictionary, Set Examples: String, Tuple, Integer
Faster for frequent modifications Safer and more secure

3. Aliasing
Aliasing occurs when two or more variables refer to the same object in memory.
Program Example
# Aliasing Example​

list1 = [1, 2, 3]​
list2 = list1​
print("list1 =", list1)​
print("list2 =", list2)​
[Link](4)​
print("After modification:")​
print("list1 =", list1)​
print("list2 =", list2)
Output
list1 = [1, 2, 3]​
list2 = [1, 2, 3]​

After modification:​
list1 = [1, 2, 3, 4]​
list2 = [1, 2, 3, 4]
Explanation
●​ list2 = list1 does not create a new list.
●​ Both variables refer to the same list object.
●​ Changes made through one variable are reflected in the other.

Diagram of Aliasing
list1 ──┐​
├──> [1, 2, 3, 4]​
list2 ──┘
Both variables point to the same memory object.

Q9. Develop a program that simulates a simple stopwatch that records random time
intervals and calculates the average elapsed time. (Dec2025/ Jan 2026)

Solution:
Q10. What is the purpose of the __init__() and __str__() method in Python
classes? (Dec2025/ Jan 2026)

Solution:

__init__():​
Every class should have this method with the special name __init__. This initializer method is
automatically called whenever a new object is created. It gives the programmer the opportunity
to set up the attributes required within the new object by giving them their initial state/values

__str__():
this method allows every instance to produce a string representation of itself. By using
this special name, the Python interpreter will automatically use our code whenever it
needs to convert a Class object to a string.

__init__() is automatically called when an object is created. It initializes the object attributes.

__str__() returns the string representation of the object.

When print(s1) is executed, Python automatically calls the __str__() method.

Q11. Write a method halfway() in the Point class that returns the midpoint between two
points. Use the points:(3, 4) and (5, 12) and display the midpoint.

Solution:
Q12. What is the purpose of the self parameter in Python classes?

Solution:
the self parameter is automatically set to reference the newly created object that needs to be
initialized It acts as a reference to the specific object instance so that you can access and
modify its attributes and methods.

You can choose any name for this parameter but, self is the standard convention. when you call
a method, you do not explicitly supply an argument to match the self parameter, as this is done
for us, behind our back.
[Link] and [Link] refer to the attributes of the current object. When [Link]() is called,
Python automatically passes s1 as the self parameter. Thus, self is used to access the data
members and methods of a class object.

Q13. Define a function that takes TWO objects representing complex numbers and
returns a new complex number with the sum of two complex numbers. Define a
suitable class ‘Complex’ to represent the complex number. Develop a program to read
N (N >=2) complex numbers and to compute the addition of N complex numbers.

Solution:
Q14. Define class and object. Explain with syntax and an example how to define a class
in python. How to initiate a class and how the class members are accessed (Dec2025/
Jan 2026)

Solution:
A class is a user-defined template used to create objects. It bundles data (attributes) and
behavior (methods) together into a single logical unit . Objects contain both data and
functionality together.

Syntax:

class ClassName:
# Class attribute
variable = value
# Constructor
def __init__(self, parameter):
[Link] = parameter
# Method
def method_name(self):
print("Hello")
Using the initializer method the class is initiated. Class members are accessed using dot
operator.

Module 5 OOPS, INHERITANCE and EXCEPTIONS


Q1. Create a Python class Point with attributes x and y. Demonstrate sameness using
'is' operator, deep equality using ==, and show the effect of mutability when modifying
one reference. (Dec2025/ Jan 2026)

Solution

shallow equality because it compares only the references, not the contents of the objects.

To compare the contents of the objects — deep equality is used for which we can write a
function called same_coordinates as shown in the example.

Q2. Explain the term objects are mutable with an example. (Dec2025/ Jan 2026)

Solution

We can change the state of an object by making an assignment to one


of its attributes. For example, to grow the size of a rectangle without
changing its position, we could modify the values of width and height
as shown in the example below.
Q3. What is polymorphism? Develop a program to illustrate polymorphism by defining
a common interface method in two different classes. (Dec2025/ Jan 2026)

Solution
For example, the multadd operation takes three parameters; it
multiplies the first two and then adds the third. This function will work
for any values of x and y that can be multiplied and for any value of z
that can be added to the product.

In the first case, the Point is multiplied by a scalar and then added to
another Point. In the second case, the dot product yields a numeric
value, so the third parameter also has to be a numeric value. A
function like this that can take arguments with different types is called
polymorphic

Q4. What is operator overloading? Define a Class Complex. Overload the + operator to
add two complex numbers. Write a Python program to read N (N2) complex numbers
and find their cumulative sum using operator overloading.

Solution

Different meanings for the same operator when applied to different


types. For example, + in Python means quite different things for
integers and for strings. This feature is called operator overloading.
Q5. What is a modifier function? How is it different from a pure function?

Solution

A modifier function is a function that changes or modifies the state of


an object or data. It performs operations that alter the values of
variables, attributes, or data structures.

A pure function is a function that does not modify external data or object
state. Always returns the same output for the same input. It has no side
effects.

Example of pure and modifier functions are shown below


Q6. Briefly explain Assertion and raise an exception. (Dec2025/ Jan 2026)

Solution
Assertion :

An assertion is used to check whether a condition is true or false during program execution .

If the condition is false, Python stops the program and raises an AssertionError.

Syntax: assert condition, “message”


Example code:
Raise an Exception :
The raise statement is used to manually generate an exception when a specific condition
occurs.
Syntax: raise Exception(“message”)
Example code:
Q7. Explain the need for exception handling in Python. Develop a program to illustrate:
try, except, close, finally block and also show how to raise an exception. (Dec2025/ Jan
2026)

Solution
Exception handling is needed to handle runtime errors and prevent abnormal termination of
the program. It helps in maintaining the normal flow of execution.

Advantages of exception handling in Python :


a. Prevents program crash
b. Handles errors gracefully
c. Improves reliability of programs
d. Displays proper error messages

The interpreter executes the block under the try statement, and monitors for exceptions. If one
occurs, the interpreter moves to the except statement; it executes the excect block if the
exception raised matches the exception requested in the except statement. If no exception
occurs, the interpreter skips the block under the except clause. An else block is executed after
the try one, if no exception occurred. A finally block is executed in any case.

You might also like