0% found this document useful (0 votes)
7 views48 pages

Unit IV - Qb&Ak Python

The document contains a series of Python programming tasks and examples, including functions for file manipulation, exception handling, and user-defined exceptions. It covers topics such as reading and writing files, handling errors, and creating a package structure for modular code. Additionally, it includes a matching exercise for Python packages and modules related to various concepts in programming.
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)
7 views48 pages

Unit IV - Qb&Ak Python

The document contains a series of Python programming tasks and examples, including functions for file manipulation, exception handling, and user-defined exceptions. It covers topics such as reading and writing files, handling errors, and creating a package structure for modular code. Additionally, it includes a matching exercise for Python packages and modules related to various concepts in programming.
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

UNIT IV- QUESTION BANK-ANSWER KEY

PART A
1(i)Aditi has used a text editing software to type some text. After saving the article as
[Link], she realised that she has wrongly typed alphabet J in place of alphabet I
everywhere in the article.
Write a function definition for JTOI() in Python that would display the corrected version of
entire content of the file [Link] with all the alphabets "J" to be displayed as an
alphabet "I" on screen.
Example:
If Aditi has stored the following content in the file
def JTOI():
file = open("/content/[Link]", "r")
data = [Link]()
[Link]()
# Replace J with I
corrected = [Link]("J", "I")
print("Corrected Content:\n")
print(corrected)
JTOI()
1(ii)Consider the file structure given below. Write Python program to
delete all the files and subdirectories from the Extinct_Animals Directory.
Step 1: Create Sample Folder Structure

import os

# Create folders
[Link]("/content/Extinct_Animals/Africa/Asia",
exist_ok=True)

# Create files
open("/content/Extinct_Animals/Africa/Asia/Koala_Lemur.txt",
"w").close()
open("/content/Extinct_Animals/Africa/Bonin_Thrush.rtf",
"w").close()

print("Demo structure created!")


Delete All Files & Subdirectories

import os
def delete_extinct_animals():
path = "/content/Extinct_Animals"
for root, dirs, files in [Link](path, topdown=False):
# Delete files
for file in files:
[Link]([Link](root, file))
# Delete folders
for dir in dirs:
[Link]([Link](root, dir))
print("All files and subdirectories deleted!")
# Call function
delete_extinct_animals()
2(i)Create a Python program to read a file named "[Link]," where each line contains
a student's name and their corresponding grade (a floating-point number). Calculate
and print the average grade of all students.
[Link]
# Program to calculate average grade Aditi 85.5
file = open("/content/[Link]", "r") Rahul 78.0
total = 0 Sneha 92.5
count = 0 Aman 88.0
for line in file:
parts = [Link]() # Split name and grade
grade = float(parts[1]) # Convert grade to float
total += grade
count += 1
[Link]()
average = total / count
print("Average Grade:", average)

Average Grade: 86.0


ii)The provided image contains the content of a text file named "read_demo.txt"
consisting of 8 lines of text, each numbered from 1 to 8.

Your task is to write a Python program that reads specific lines from the file based on
the line numbers provided below:
a) Read and print the content of line 3 from the file.
b) Read and print the content of line 5 from the file.
c) Read and print the content of line 7 from the file.
Implement the program to accomplish the tasks outlined above.
# Open the file
with open("/content/[Link]", "r") as file:
lines = [Link]()
# a) Read line 3
print("Line 3:", lines[2].strip())
# b) Read line 5
print("Line 5:", lines[4].strip())
# c) Read line 7
print("Line 7:", lines[6].strip())
iii)Write a function AMCount() in Python, which should read each character of a text file
[Link], should count and display the occurrence of alphabets A and M (including
small cases a and m too).
For Example:
If the file content is as follows:
Updated information
As simplified by official websites.
The EUCount() function should display the output as:
A or a:4
M or m :2
def AMCount():
file = open("/content/[Link]", "r")
data = [Link]()
[Link]()
countA = 0
countM = 0
for ch in data:
if ch == 'A' or ch == 'a':
countA += 1
elif ch == 'M' or ch == 'm':
countM += 1
print("A or a:", countA)
print("M or m:", countM)
3(i)A school’s computer system stores daily student attendance details in a file
named attendance_log.txt.
The system needs to perform the following tasks:
 Add a new attendance entry for today at the end of the file without removing
existing records.
 At the end of the month, erase the entire file and write a fresh heading:
Monthly Attendance Summary
 A teacher wants to display the complete contents of the file on the screen
without modifying anything in it.
Write the Python code statements/functions needed to complete all three tasks.
Add a new attendance entry for today at the end of the file without removing existing
records.
def add_attendance(entry):
with open("/content/Attendance_log.txt", "a") as file:
[Link](entry + "\n")
print("Added:", entry)

# Call function
add_attendance("Sneha Present")

# Display file
with open("/content/Attendance_log.txt", "r") as file:
print("\nFile Content:\n")
print([Link]())
At the end of the month, erase the entire file and write a fresh heading:
Monthly Attendance Summary
def reset_file():
file = open("/content/Attendance_log.txt", "w")
[Link]("Monthly Attendance Summary\n")
[Link]()

print("File has been reset successfully!")


A teacher wants to display the complete contents of the file on the screen without
modifying anything in it.

def display_attendance():
file = open("/content/Attendance_log.txt", "r")
data = [Link]()
print(data)
[Link]()
3(ii)What will be the output of the following code?
try:
x = 10 / 0
except ZeroDivisionError:
print("Division by zero!")
except Exception as e:
print(f"An error occurred: {e}")

The statement x = 10 / 0 raises a ZeroDivisionError because division by zero is not


allowed.

The try block immediately jumps to the first matching except block:

except ZeroDivisionError:
print("Division by zero!")

So, the output will be:

Division by zero!
3(iii)In the provided Python code, what happens if the user enters a non-integer
value when prompted to enter a number? How does the program handle this
situation?
try:
num = int(input("Enter a number: "))
print("You entered:", num)
except ValueError:
print("Error: Invalid input. Please enter a valid integer.")

When the user enters a non-integer value:


int(input()) raises a ValueError
The except ValueError block catches it
The program prints an error message instead of crashing

If the user enters a non-integer value, a ValueError occurs.


The program catches this exception using the except block and prints:
"Error: Invalid input. Please enter a valid integer."
3(iii)(ii)In the provided Python code, what happens if you attempt to divide the
number 10 by zero? How does the program handle this situation?
try:
x = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero!")

When dividing 10 by 0:
Python raises a ZeroDivisionError
The except ZeroDivisionError block handles it
The program prints an error message

If 10 is divided by 0, a ZeroDivisionError occurs.


The program catches this exception and prints:
"Error: Division by zero!"
4(i)Write a Python program that prompts the user to input an integer and raises a
ValueError exception if the input is not a valid integer.

try:
num = int(input("Enter an integer: "))
print("You entered:", num)
except ValueError:
print("Error: Invalid input. Please enter an integer.")

int(input()) tries to convert input into an integer


If the input is not valid (like "abc"), it raises a ValueError
The except block catches it and prints an error message

Output
Enter an integer: abc
Error: Invalid input. Please enter an integer.
4(ii)What are the error messages that are displayed for the following
exceptions?
a. Accessing a non-existent list item
b. Accessing a key that isn’t in the dictionary
c. Trying to open a non-existent file
a) Accessing a non-existent list item
Exception: IndexError
lst = [1, 2, 3]
print(lst[5])
Error message: IndexError: list index out of range
b) Accessing a key that isn’t in the dictionary
Exception: KeyError
d = {"a": 1, "b": 2}
print(d["c"])
Error message: KeyError: 'c'

c) Trying to open a non-existent file


Exception: FileNotFoundError
open("[Link]")
Error message: FileNotFoundError: [Errno 2] No such file or directory: '[Link]'
4(iii)Using these two real-life examples shown in the image, write a Python program
that demonstrates exception handling:
# Example 1: Watching video interrupted by internet issue
try:
print("Watching a video on YouTube...")

# Simulating internet disconnection


raise ConnectionError("Internet disconnected!")

print("Video is playing smoothly.")

except ConnectionError as e:
print("Exception:", e)
print("Video stopped due to network issue.")

First example → simulates an internet failure using ConnectionError


try block → normal activity
raise → creates the problem (exception)
output
except → handles the problem gracefully
# Example 2: Car puncture situation
try:
print("\nDriving the car...")

# Simulating car puncture


raise Exception("Tyre punctured!")

print("Car is running smoothly.")

except Exception as e:
print("Exception:", e)
print("Handling: Repairing the tyre... Car can move again.")

Second example → simulates a car puncture using a general Exception


try block → normal activity
raise → creates the problem (exception)
except → handles the problem gracefully

output
5(i)For the given scenario,

write a Python program using a user-defined exception that checks a username


entered by the user. Your program should raise a custom exception if the username
contains any space and display an appropriate error message. If no space is found,
it should display that the username is valid.
try:
username = input("Enter username: ")
# Check for space
if " " in username:
raise Exception("Username should not contain spaces!")
print("Valid username!")
except Exception as e:
print("Error:", e)
(ii)Generalize a case study on the getting the students mark statements and
analysis with Try and Except Statement – Catching Exceptions

Case Study: Student Marks Entry System Using Exception Handling


Problem Statement
In a school system, a program is required to:
• Accept marks from students
• Ensure the marks entered are valid (numeric and within range)
• Handle errors like invalid input or out-of-range values
• Prevent the program from crashing
try:
marks = int(input("Enter student marks (0–100): "))
# Check if marks are within valid range
if marks < 0 or marks > 100:
raise ValueError("Marks should be between 0 and 100.")
print("Marks entered:", marks)
except ValueError as e:
print("Error:", e)

try block → Takes user input and checks validity


If input is not a number → ValueError occurs
If marks are outside 0–100 → manually raise ValueError
except block → catches error and shows message

Possible Scenarios
Input Result
85 Valid marks displayed
-10 Error: Marks should be between 0 and 100
150 Error: Marks should be between 0 and 100
abc Error: invalid literal for int()
Part B
1)(i)Match the Following
Concept Package/Module
1. Machine Learning a. numpy
2. Data Analysis b. venv
3. File and Directory Handling c. matplotlib
4. Web Scraping d. os
5. Creating Virtual Environments e. sklearn
6. Plotting Graphs f. beautifulsoup4
7. Numerical Computations g. datetime
8. Date and Time Operations h. pandas

Concept Correct Package/Module


1. Machine Learning e. sklearn
2. Data Analysis h. pandas
3. File and Directory Handling d. os
4. Web Scraping f. beautifulsoup4
5. Creating Virtual Environments b. venv
6. Plotting Graphs c. matplotlib
7. Numerical Computations a. numpy
8. Date and Time Operations g. datetime
1(ii)You are given the Python project structure shown in the image.
Using the information Formulate Python code in the appropriate files to:

 Import functions from the modules inside the mypackage subpackage into one of the
top-level scripts.
 Use at least one function from each module inside mypackage to perform a meaningful
operation (such as a calculation or message output).
 Ensure that mypackage is recognized as a package and can be imported without errors.
 Demonstrate how another script in the top-level directory would test the package
functions after importing them.
1. mypackage/__init__.py
👉 Makes the folder a package + simplifies imports
from .areafunctions import area_circle, area_rectangle
from .mathfunctions import add, multiply

[Link]/[Link]

import math
def area_circle(radius):
return [Link] * radius * radius
def area_rectangle(length, width):
return length * width

3. mypackage/[Link]

def add(a, b):


return a + b
def multiply(a, b):
return a * b
4. [Link]
👉 Imports functions and performs operations

from mypackage import area_circle, area_rectangle, add, multiply


print("Circle Area:", area_circle(5))
print("Rectangle Area:", area_rectangle(4, 6))
print("Addition:", add(10, 5))
print("Multiplication:", multiply(3, 4))

5. [Link] (Testing Script)


👉 Demonstrates testing after importing

import mypackage
print("Testing Package Functions")
print("Circle Area:", mypackage.area_circle(3))
print("Rectangle Area:", mypackage.area_rectangle(2, 5))
print("Addition:", [Link](7, 8))
print("Multiplication:", [Link](2, 6))
2(i)Write a Python script in a separate file that:
Imports all functions from simple_math.py.
Imports only the concatenation () function from
simple_string.py.
 Takes user input to perform:
 Addition of two numbers
 Multiplication of two numbers
 Concatenation of two strings
 Displays the results.
Also write the required content for __init__.py to allow importing the package using: import functions
Using the directory structure shown in the image below:
1. simple_math.py

def addition(a, b):


return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b

2. simple_string.py
def concatenation(s1, s2):
return s1 + s2
def findLength(s):
return len(s)

3. __init__.py

import functions
from .simple_math import *
from .simple_string import concatenation
Main Script (e.g., [Link])

import functions

# Taking user input


a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

s1 = input("Enter first string: ")


s2 = input("Enter second string: ")

# Operations
add_result = [Link](a, b)
mul_result = [Link](a, b)
concat_result = [Link](s1, s2)

# Display results
print("Addition:", add_result)
print("Multiplication:", mul_result)
print("Concatenation:", concat_result)
2(ii)Write the python code for the following scenario

1. Module: random_gen.py

import random

def generate_numbers(min_val, max_val, count):


numbers = []
for i in range(count):
[Link]([Link](min_val, max_val))
return numbers
2. Package File: __init__.py
from .random_gen import generate_numbers

[Link] Program: [Link]

import functions
# user input
min_val = int(input("Enter minimum: "))
max_val = int(input("Enter maximum: "))
count = int(input("How many numbers: "))
# call function
nums = functions.generate_numbers(min_val, max_val, count)
# display result
print("Answer:", *nums)
3(i)Identify the module import error and rewrite the corrected import statement

Identify the Error


The error shown is: import nump # incorrect
👉 Problem:The module name is misspelled nump ❌ does not exist
👉 That’s why Python gives: ModuleNotFoundError: No module named 'nump'

Correct Import Statement Correct Full Code


import numpy import numpy
arr = [Link]([1, 2, 3])
print(arr)
3(ii)Fill in the blanks
[Link] install an external module like pandas, we use the command: ________ install pandas
[Link] allow Python to treat a folder as a package, we must include a file named ___________.
[Link] built-in module used for generating random values is __________.
[Link] import only a specific function from a module, we use: from module_name ___
function_name

1. pip
2. __init__.py
3. random
4. import
3(iii)You are building a student report generator. Justify whether you should use:
built-in modules, external modules or custom modules. Give reasons and examples.

Student Report Generator – Which Modules to Use?


When building a student report generator, we should use a combination of built-in
modules, external modules, and custom modules.
1. Built-in ModulesUseful for basic tasks like date, file handling, etc.
Examples:
datetime → to add report date
os → to manage iles/folders

Example Code:

import datetime
print([Link]())

2026-03-31
External Modules- Provide advanced features, Save time and effort
Examples:
pandas → to handle student data (tables)
matplotlib → to generate charts/graphs
Example Code:

import pandas as pd
data = {"Name": ["Alice"], "Marks": [90]}
df = [Link](data)
print(df)

👉 Used for data analysis and report formatting


3. Custom Modules
Organize project code
Reuse your own functions
Examples:
[Link] → calculate grades
[Link] → generate report
Example Code: [Link] (Assign Grade)
# [Link] def calculate_grade(avg):
def total_marks(marks_list): if avg >= 90:
return sum(marks_list) return "A"
def average_marks(marks_list): elif avg >= 75:
return sum(marks_list) / len(marks_list) return "B"
elif avg >= 60:
return "C"
elif avg >= 50:
return "D"
else:
return "F"
[Link]

import marks
import grades
# input marks
marks_list = [80, 90, 70]
total = marks.total_marks(marks_list)
average = marks.average_marks(marks_list)
grade = grades.calculate_grade(average)
print("Total:", total)
print("Average:", average)
print("Grade:", grade)

A student report generator should use:

✔ Built-in modules → for basic operations

✔ External modules → for data handling and visualization

✔ Custom modules → for organizing project logic


4(i)A junior developer wrote 400 lines of repeated code in 4 files. Explain how you
would convert these repeated functions into a module and import it properly across all
files.
Problem Situation
A junior developer has:
❌ Written 400 lines of repeated code
❌ Duplicated the same functions in 4 different files
👉 This leads to:
Difficult maintenance
Code duplication
Higher chance of errors
Solution: Convert into a Module

Step 1: Identify Common Functions


👉 Find repeated functions like:
def calculate_total(a, b):
return a + b # [Link]
def calculate_total(a, b):
Step 2: Create a Module return a + b
👉 Create a new file: [Link] def calculate_average(a, b):
👉 Move all repeated functions into it: return (a + b) / 2
Step 3: Remove Duplicate Code
👉 Delete repeated functions from all 4 files

Step 4: Import Module in Each File

Method 1: Import whole module

import utils
print(utils.calculate_total(5, 3))

Method 2: Import specific functions


from utils import calculate_total
print(calculate_total(5, 3)) Benefits of This Approach
✔ Eliminates code duplication
Step 5: Use Across All Files ✔ Improves readability
👉 In all 4 files, just add: ✔ Easier maintenance (change in one place only)
✔ Promotes reusability
import utils

👉 Repeated functions should be moved into a separate module (e.g., [Link]), and then
imported into all files using import utils or from utils import function_name, which
reduces duplication and improves maintainability.
4(ii)Your team wants to reduce repeated code across 15 different Python files. Explain
how you would reorganize the code using modules and packages without breaking
existing functionality.

Problem
Your team has:
❌ 15 Python files
❌ Repeated code across multiple files
❌ Difficult maintenance and updates
Goal
👉 Reorganize code using modules and packages
👉 Without breaking existing functionality
Step-by-Step Solution
Step 1: Identify Common Code
Find repeated functions (e.g., calculations, validations, utilities)
Example:
def calculate_total(a, b):
return a + b
Step 2: Create Modules
Example: math_utils.py
👉 Group related functions into modules:
utils/ def add(a, b):
math_utils.py return a + b
string_utils.py
Step 3: Create a Package
👉 Organize modules into a package:
utils/
__init__.py
math_utils.py
string_utils.py
👉 __init__.py ensures it works as a package

Step 4: Update Imports in All Files


Before ❌ (repeated code in each file)
def add(a, b):
return a + b
After ✅ (import from module)
Step 6: Test the System
from utils.math_utils import add Run all 15 files
Verify outputs remain unchanged
Step 5: Maintain Compatibility
To avoid breaking existing code:
Option 1: Keep same function names
👉 Do not change function names or behavior
Option 2: Use wrapper functions (if needed)
# old file
from utils.math_utils import add as calculate_total
5(i)You have two Python files in the same folder:
[Link]
from file2 import greet
def hello():
return "Hello from file1"
print(greet())
[Link]
from file1 import hello
def greet():
return "Greetings from file2"
If you run [Link], what will happen? Explain the error (if any) and suggest a fix.
The program will result in a circular import error
Why does this happen?
Step-by-step execution:
You run [Link]
It tries:
from file2 import greet
Now Python starts loading [Link]
Inside [Link]:
from file1 import hello
👉 It again tries to import file1
But [Link] is not fully loaded yet
👉 So Python gets stuck in a loop:
ile1 → ile2 → ile1 → ile2 → ...
❌ Error Produced
ImportError: cannot import name 'hello' from partially initialized module 'file1'
Fix : Create a separate module

Create [Link]
# [Link]
def hello():
return "Hello from file1"

def greet():
return "Greetings from file2"

[Link]
from utils import greet
print(greet())

[Link]
from utils import hello

Running [Link] causes a circular import error because both files import each other. This
results in a partially initialized module error. It can be fixed by moving imports inside
functions or restructuring code into a separate module.
ii)module_name = input("Enter module: ")
mod = __import__(module_name)
print(mod.__name__)
If the user inputs math, what will be the output? What are potential risks of using
__import__() with dynamic input?

If the user enters:


math
Output:
math
Because:
__import__("math") loads the built-in math module
mod.__name__ returns the module name → "math“

Risk:
• Using __import__() with user input is dangerous because:
• User can import unwanted modules (like os)
• It may cause security problems

You might also like