PYTHON MODULE
1 a. Difference between a module and a package in Python
Module: A module is a single file containing Python definitions and
statements, such as functions, classes, and variables. It is used to
organize and reuse code. A module has a .py extension. For
example, a file math_functions.py is a module.
Package: A package is a collection of related modules organized in
directories. A package may contain sub-packages, modules, and
other resources. A package has a special __init__.py file to mark it as
a Python package. For example, a directory math containing
[Link], [Link], and [Link] is a package.
b. Writing a [Link] module and importing it into another
script
[Link]:
# [Link]
# Addition function
def add(a, b):
return a + b
# Subtraction function
def subtract(a, b):
return a - b
# Multiplication function
def multiply(a, b):
return a * b
# Division function
def divide(a, b):
return a / b if b != 0 else "Cannot divide by zero"
# Power function
def power(a, b):
return a ** b
Using the module in another script:
# [Link]
import calculator
# Using the functions from the calculator module
print([Link](10, 5)) # Output: 15
print([Link](10, 5)) # Output: 5
print([Link](10, 5)) # Output: 50
print([Link](10, 5)) # Output: 2.0
print([Link](2, 3)) # Output: 8
c. Analysing and modifying the import statement
The given code is:
from math import sqrt, pow
print(pow(2, 3), sqrt(25))
Analysis of Output:
pow(2, 3) calculates 2 raised to the power of 3, which results in 8.
sqrt(25) calculates the square root of 25, which results in 5.0.
So, the output will be:
8 5.0
Modified Code to Import Only sqrt Using Aliasing:
from math import sqrt as square_root
print(square_root(25))
Now, you are importing sqrt from the math module using an alias
square_root, and you can use square_root(25) instead of sqrt(25). The
output will still be:
5.0
2 a. How to import a specific function from a module? Explain with
an example
To import a specific function from a module, you can use the from
module_name import function_name syntax. This allows you to access
only the specific function from the module, rather than importing the
entire module.
Example: Let's say we have a module math_operations.py with the
following content:
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
Now, if you only want to use the add function, you can import it
specifically as follows:
from math_operations import add
result = add(10, 5)
print(result) # Output: 15
This imports only the add function, and you can directly use it in your
script.
b. Program that handles ValueError if the input is not numeric
# Program to handle ValueError if the input is not numeric
try:
number = input("Please enter a number: ")
number = int(number) # Convert input to an integer
print(f"The number you entered is: {number}")
except ValueError:
print("That's not a valid number! Please enter a numeric value.")
Explanation:
The program uses input() to get a number from the user.
It attempts to convert the input to an integer using int().
If the input is not a valid number (for example, if the user enters a
string), it will raise a ValueError, which is caught by the except
block, and a message is printed.
c. Deciding between import [Link] vs. from package
import module
import [Link]:
o This is useful when you want to access several functions,
classes, or variables from the module, or if the module name
might conflict with other names in your code.
o When you use import [Link], you access functions
or classes from the module by prefixing them with the module
name.
Example:
import math_operations
result = math_operations.add(10, 5)
print(result) # Output: 15
This syntax is better when you want to keep the module's namespace
clear and avoid name conflicts.
from package import module:
o This is used when you want to import the entire module into
the current namespace. You don't need to reference the
module name when calling functions or using variables.
o This is convenient when you only need a few specific functions
from a module and want to avoid repeating the module name.
Example:
from math_operations import add
result = add(10, 5)
print(result) # Output: 15
This syntax is preferred when you are going to use a specific module's
functionality extensively in the code and want to avoid repeating the
module name.
Conclusion:
Use import [Link] when you want to use multiple
components from the module or avoid conflicts with other names in
your code.
Use from package import module when you want to directly use the
module and don't mind importing everything from it.
3 a. Purpose of the __init__.py file in a Python package
The __init__.py file is used to mark a directory as a Python package. It
allows you to organize modules into a package and provides an
initialization point for the package. When you import a package, Python
executes the code inside the __init__.py file (if any), enabling initialization
logic.
Additionally, __init__.py can be used to define what should be exposed
when the package is imported, including importing specific modules or
classes from the package.
Without the __init__.py file, Python would not recognize the directory as a
package, and you would not be able to import modules from it.
Example:
# directory structure:
# mypackage/
# ├── __init__.py
# ├── [Link]
# └── [Link]
# __init__.py content could be:
from .module1 import function1
from .module2 import function2
This allows you to import mypackage and use function1 and function2
directly without referencing the individual modules:
import mypackage
mypackage.function1()
mypackage.function2()
b. Python program to open a file, write some text, and then read
it back
# Opening the file in write mode to write text
with open("[Link]", "w") as file:
[Link]("Hello, this is a sample text.")
# Opening the file in read mode to read back the text
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Explanation:
1. The with open() statement ensures that the file is properly closed
after reading or writing.
2. In the first block, we open the file in write mode ("w") and write
some text to it.
3. In the second block, we open the same file in read mode ("r") and
print its contents.
c. Analysing the code and determining what exception might be
raised and why
num = int(input("Enter a number: "))
print(100 / num)
Possible Exceptions:
1. ValueError: If the user enters something that cannot be converted
to an integer (e.g., a string like "abc"), the int() function will raise a
ValueError. This happens because int() expects a valid number string
to convert into an integer.
Example input: "abc"
Explanation: The int() function will fail because it cannot parse a non-
numeric string into an integer.
2. ZeroDivisionError: If the user enters 0 as the number, the division
100 / num will attempt to divide by zero, resulting in a
ZeroDivisionError. This is because division by zero is undefined in
mathematics, and Python raises an exception in such cases.
Example input: 0
Explanation: The division 100 / 0 is not allowed and will raise a
ZeroDivisionError.
Conclusion:
The two potential exceptions in the code are ValueError and
ZeroDivisionError.
o ValueError occurs if the input cannot be converted to an
integer.
o ZeroDivisionError occurs if the user enters 0 for the division
operation.
4 a. What is Encapsulation in OOP, and how is it achieved in
Python?
Encapsulation is an object-oriented programming (OOP) concept that
bundles data (attributes) and the methods (functions) that operate
on the data into a single unit—a class. It also restricts direct access to
some components, which is known as data hiding.
In Python, encapsulation is achieved using:
Public members (default): Accessible from anywhere.
Protected members (prefix with _): Conventionally intended for
internal use.
Private members (prefix with __): Name mangling is used to
prevent direct access.
Example:
class Person:
def __init__(self, name, age):
[Link] = name # public
self._age = age # protected
self.__ssn = "123-45-6789" # private
def display(self):
print(f"Name: {[Link]}, Age: {self._age}")
p = Person("Alice", 30)
print([Link]) # OK
print(p._age) # OK but not recommended
# print(p.__ssn) # Error: AttributeError
b. Python Script to Write and Read File
Here is the correct version of the file operation script:
# Writing to the file
with open("[Link]", "w") as file:
[Link]("Hello, Python!")
# Reading the file
with open("[Link]", "r") as file:
content = [Link]()
print(content)
c. Exception Handling Code Analysis and Output
Given Code:
try:
x=1/0
except ValueError:
print("Value Error occurred")
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution complete")
Step-by-Step Execution:
1. x = 1 / 0 causes a ZeroDivisionError.
2. Python looks for a matching except block.
3. It skips except ValueError (no match).
4. It matches except ZeroDivisionError and executes:
5. Cannot divide by zero
6. After the exception is handled, it always runs the finally block:
7. Execution complete
✅ Final Output:
Cannot divide by zero
Execution complete
5 a. Difference between a class and an object in Python:
Class:
A class is a blueprint or template for creating objects. It defines
attributes and methods that the objects created from the class will
have.
Example:
class Dog:
def bark(self):
print("Woof!")
Object:
An object is an instance of a class. It is created using the class and
can use the attributes and methods defined in that class.
Example:
my_dog = Dog()
my_dog.bark() # Output: Woof!
b. Program to read a file and handle missing file error:
try:
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]()
except FileNotFoundError:
print("File not found!")
c. How to import greet() from the given package structure:
Given package structure:
my_package/
__init__.py
utils/
__init__.py
[Link] # contains greet()
To import the greet() function from [Link], you'd use:
from my_package.[Link] import greet
This assumes your working directory is set such that my_package is on
the Python path.
Let me know if you'd like a working example using this structure!
6 a. Explain inheritance with an example in Python:
Inheritance allows a class (called a child or subclass) to inherit attributes
and behavior (methods) from another class (called a parent or superclass).
This promotes code reuse.
Example:
class Vehicle:
def move(self):
print("Vehicle is moving")
class Car(Vehicle):
def honk(self):
print("Car is honking")
my_car = Car()
my_car.move() # Inherited from Vehicle
my_car.honk() # Defined in Car
Here, Car inherits the move method from Vehicle, so it can use both
move() and honk().
b. Create a simple package calculator with module basic_ops and
use it in a script:
Folder structure:
calculator/
├── __init__.py
└── basic_ops.py
Content of basic_ops.py:
# calculator/basic_ops.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Usage in a separate script (e.g., [Link]):
# [Link]
from calculator.basic_ops import add, subtract
print(add(10, 5)) # Output: 15
print(subtract(10, 5)) # Output: 5
Make sure calculator folder is in the same directory or on your Python
path.
c. Review this inheritance example and explain the unexpected
output:
class Animal:
def speak(self):
print("I make a sound")
class Cat(Animal):
def speak(self):
print("Meow")
pet = Animal()
[Link]() # Expected "Meow" by the user
Explanation:
The user expected "Meow" because they likely thought pet was an
instance of Cat, but it's actually an instance of Animal.
pet = Animal() creates an Animal, not a Cat.
So [Link]() calls Animal’s version of speak, which prints "I make
a sound".
To get "Meow", the line should be:
pet = Cat()
Also, the indentation is incorrect in this code, which would cause a syntax
error. It should be properly indented like this:
class Animal:
def speak(self):
print("I make a sound")
class Cat(Animal):
def speak(self):
print("Meow")
pet = Cat()
[Link]() # Now this prints "Meow"
Sure! Here's the complete answer to question 7, clearly broken down and
written without using functions.
7 a. Difference between read() and readline() in Python:
read():
o Reads the entire contents of a file as a single string.
o Useful when you want all the data at once.
o Example:
o file = open("[Link]", "r")
o content = [Link]()
o print(content)
o [Link]()
readline():
o Reads the next line from the file (up to the next newline \n).
o Useful when processing files line by line.
o Example:
o file = open("[Link]", "r")
o line = [Link]()
o print(line)
o [Link]()
b. Create a Python package shapes with [Link] and
[Link]
Folder structure:
shapes
__init__.py
[Link]
[Link]
Content of [Link]:
# shapes/[Link]
pi = 3.1416
def area(radius):
return pi * radius * radius
Content of [Link]:
# shapes/[Link]
def area(length, width):
return length * width
Usage in a script (e.g., [Link]):
# [Link]
from [Link] import area as circle_area
from [Link] import area as rectangle_area
print(circle_area(5)) # Output: 78.54
print(rectangle_area(4, 6)) # Output: 24
c. Handling multiple exceptions – Order and example:
Exceptions should be ordered from most specific to most
general.
Python checks exceptions top-down, so more specific exceptions
must come before broader ones like Exception.
Example:
try:
number = int(input("Enter a number: "))
result = 10 / number
print("Result:", result)
except ZeroDivisionError:
print("You can't divide by zero.")
except ValueError:
print("Invalid input. Please enter a number.")
except Exception as e:
print("Something went wrong:", e)
Why this order?
If Exception is written first, it will catch everything, and the
specific ones (ZeroDivisionError, ValueError) will never be reached.
Absolutely! Here's the full breakdown for each part of your question,
without using functions.
8 a. Difference between Compile-time and Runtime Errors:
Compile-time Errors:
o These errors occur when the code is being parsed or
translated into bytecode.
o Python is an interpreted language, so this happens during the
initial check when the script runs.
o Examples include syntax errors like missing colons,
unmatched parentheses, or indentation issues.
o Example:
o if x == 5 # SyntaxError: expected ':'
o print("x is 5")
Runtime Errors:
o These occur while the program is running.
o The code may be syntactically correct, but still cause errors
like dividing by zero or accessing an undefined variable.
o Example:
o x = 10 / 0 # ZeroDivisionError
b. Read a CSV file and convert it into a dictionary:
Assuming the file [Link] looks like this:
name,age,city
Alice,30,New York
Bob,25,London
The code to read and convert into a dictionary:
import csv
file = open("[Link]", "r")
reader = [Link](file)
data_list = []
for row in reader:
data_list.append(dict(row))
print(data_list)
[Link]()
Output:
[{'name': 'Alice', 'age': '30', 'city': 'New York'}, {'name': 'Bob', 'age': '25',
'city': 'London'}]
c. Count the number of words in a given text file:
file = open("[Link]", "r")
content = [Link]()
words = [Link]()
word_count = len(words)
print("Number of words:", word_count)
[Link]()
This reads the file, splits the content by whitespace, and counts the
number of words.
Sure! Here's a complete and clear explanation for all parts of your
question — all written without using functions, as requested.
9 a. Use of try, except, and finally in Python exception handling:
try block:
Used to wrap code that might raise an exception.
except block:
Contains the code that runs if an exception occurs in the try block.
finally block:
Runs no matter what — whether an exception was raised or not.
It's often used to release resources (like closing a file or database
connection).
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("You can't divide by zero.")
except ValueError:
print("Invalid input. Enter a number.")
finally:
print("This block always executes.")
b. Inheritance behavior and output of the given code:
class Parent:
def show(self):
print("Parent class")
class Child(Parent):
pass
obj = Child()
[Link]()
Analysis:
The Child class inherits from the Parent class.
Since Child does not override the show() method, it uses the
show() method defined in Parent.
When [Link]() is called, it prints:
Parent class
Conclusion:
This shows simple inheritance — the child inherits methods and
attributes from the parent unless overridden.
c. Define a Student class with name, grade, and display_info
method:
class Student:
def __init__(self, name, grade):
[Link] = name
[Link] = grade
def display_info(self):
print("Name:", [Link])
print("Grade:", [Link])
student1 = Student("Alice", "A")
student1.display_info()
Output:
Name: Alice
Grade: A
This demonstrates how to define a class with attributes and a method to
display them, then create an object and call the method.
Absolutely! Here's your answer for all parts of the question, clearly
explained without using functions, as requested.
10 a. What is a ZeroDivisionError in Python, and when does it
occur?
ZeroDivisionError is a built-in exception in Python.
It occurs when a number is divided by zero, which is
mathematically undefined.
Example:
x = 10
y=0
result = x / y # Raises ZeroDivisionError
Error Message:
ZeroDivisionError: division by zero
This is a runtime error and will crash the program unless properly
handled with a try-except block.
b. Script using os module to check if a file exists:
import os
file_path = "[Link]"
if [Link](file_path):
file = open(file_path, "r")
content = [Link]()
print(content)
[Link]()
else:
print("File does not exist.")
This code checks for the file’s existence before trying to open it, avoiding
a FileNotFoundError.
c. Comparing open() vs with statement for file handling:
Using open() (manual resource management):
file = open("[Link]", "r")
content = [Link]()
print(content)
[Link]() # Must remember to close the file manually
You have to explicitly close the file using [Link]().
If an error occurs before closing, the file may stay open, which can
lead to memory leaks or file locking issues.
Using with statement (automatic resource management):
with open("[Link]", "r") as file:
content = [Link]()
print(content)
This approach automatically closes the file once the block is
exited — even if an error occurs inside the block.
It’s safer and cleaner, and is the recommended way for working
with files in Python.