BTCE | 5th Sem
Adv-Python SubjectExtra Questions

Adv-Py: Unit 3 (Book-back Questions)

Generated and Prepared By Thiruselvan (ThiruXD)

PART A — MULTIPLE CHOICE QUESTIONS (1 Mark Each)


Q1. Which file extension is used for a Python module?

  1. txt
  2. py
  3. json
  4. exe

Answer: (b) py

Explanation: A Python module is a file containing Python definitions and statements. The .py extension identifies it as a Python source file. For example, calculator.py becomes the module calculator.


Q2. Which keyword is used to import a module in Python?

  1. include
  2. import
  3. module
  4. using

Answer: (b) import

Explanation: The import statement brings code from one module into another program. Example: import math loads the math module.


Q3. What is the purpose of the as keyword in import statements?

  1. Delete a module
  2. Rename the Python file permanently
  3. Create an alias for the imported module
  4. Convert a module into JSON

Answer: (c) Create an alias for the imported module

Explanation: The as keyword creates an alternate short name (alias) for the imported module within the current program. Example: import math as m allows m.sqrt(25). It does not rename the original file.


Q4. Which function lists names available inside a module?

  1. list()
  2. names()
  3. dir()
  4. show()

Answer: (c) dir()

Explanation: The dir() function returns a list of names (functions, classes, constants, attributes) available inside an object or module. Example: dir(math) displays all names in the math module.


Q5. Which json function converts a JSON string into a Python object?

  1. json.dumps()
  2. json.loads()
  3. json.dump()
  4. json.convert()

Answer: (b) json.loads()

Explanation: json.loads() parses a JSON string and converts it into a Python object (dict, list, etc.). The ‘s’ stands for string. Example:

import json
student = json.loads('{"name": "Ravi", "age": 21}')
print(student["name"])  # Ravi

Q6. Which json function writes a Python object into a JSON file?

  1. json.write()
  2. json.save()
  3. json.dump()
  4. json.loads()

Answer: (c) json.dump()

Explanation: json.dump() writes a Python object into a file in JSON format. Example:

with open("student.json", "w") as file:
    json.dump(student, file, indent=4)

Q7. Which module is used for regular expressions in Python?

  1. regex
  2. re
  3. string
  4. pattern

Answer: (b) re

Explanation: The re module provides regular expression operations such as search(), findall(), sub(), match(), and fullmatch(). Example: import re.


Q8. Which RegEx function replaces matching text?

  1. re.sub()
  2. re.replace()
  3. re.change()
  4. re.swap()

Answer: (a) re.sub()

Explanation: re.sub(pattern, replacement, text) replaces all occurrences of the pattern with the replacement text. Example:

import re
cleaned = re.sub(r"\s+", " ", "Python    is   easy")
print(cleaned)  # Python is easy

Q9. Which exception occurs when a program tries to divide by zero?

  1. ValueError
  2. TypeError
  3. ZeroDivisionError
  4. IndexError

Answer: (c) ZeroDivisionError

Explanation: ZeroDivisionError is raised when a number is divided by zero. Example: 10 / 0 raises this exception. It is handled using:

try:
    print(10 / 0)
except ZeroDivisionError:
    print("Cannot divide by zero.")

Q10. Which file mode appends content at the end of a file?

  1. r
  2. w
  3. a
  4. x

Answer: (c) a

Explanation: Append mode (a) adds content at the end of an existing file without overwriting its current contents. Example:

with open("log.txt", "a") as file:
    file.write("New log entry\n")

PART B — SHORT ANSWER QUESTIONS (5 Marks Each)


Q11. Define a Python module. Explain any four advantages of using modules in Python programs.

Answer:

Definition: A Python module is a file with a .py extension that contains Python definitions and statements — including functions, classes, variables, and executable code. The file name becomes the module name without the .py extension. For example, a file named calculator.py becomes the module calculator.

Modules allow programmers to organize code logically by dividing a large program into smaller, manageable files, each handling one responsibility.

Four Advantages of Using Modules:

#AdvantageExplanationExample
1Code ReuseWrite once and use in many programs, avoiding duplicationUse the same tax calculation function in multiple billing programs
2OrganisationSeparate a large program into smaller logical files, improving readabilityKeep database code, validation code, and report code in separate modules
3MaintainabilityChanges can be made in one module without rewriting the full applicationUpdate one email-sending module used across the project
4TestingIndividual modules can be tested independently before integrationTest calculator functions before using them in the main program

Additional advantages: Teamwork (different developers work on different modules), reduced development time, and consistency across projects.


Q12. Explain the difference between import module, import module as alias, and from module import name with examples.

Answer:

Python provides different ways to import modules depending on how much of the module is required. Choosing the correct import style improves readability and prevents name conflicts.

Import StyleSyntaxWhen to UseExample
Import full moduleimport mathWhen many functions from the module are requiredmath.sqrt(81)
Import with aliasimport math as mWhen a shorter name improves readabilitym.sqrt(81)
Import one namefrom math import sqrtWhen only one function or variable is neededsqrt(81)
Import multiple namesfrom math import sqrt, piWhen a few selected names are neededsqrt(81), pi
Import all namesfrom math import *Generally avoided because it can create name conflictssqrt(81)

Examples:

# 1. import module
import math
print(math.sqrt(81))      # 9.0
print(math.pi)            # 3.14159...

# 2. import module as alias
import math as m
print(m.factorial(5))     # 120

# 3. from module import name
from math import sqrt, pi
print(sqrt(81))           # 9.0
print(pi)                 # 3.14159...

Key Differences:

  • import module → Access via module.name; keeps namespace clean.
  • import module as alias → Same as above but with a shorter name; commonly used for NumPy (np), Pandas (pd), Matplotlib (plt).
  • from module import name → Direct access without the module prefix; convenient but can cause name clashes.

Best Practice: Use import module or import module as alias for clarity; avoid from module import *.


Q13. What is JSON? Explain json.loads(), json.dumps(), json.load(), and json.dump() with suitable examples.

Answer:

JSON (JavaScript Object Notation) is a lightweight text format used for storing and exchanging structured data. It is widely used in web applications, APIs, configuration files, databases, and data transfer between systems.

JSON Data Types and Python Mapping:

JSON TypePython EquivalentExample
objectdict{"name": "Amit"}
arraylist[10, 20, 30]
stringstr"Python"
numberint or float25 or 3.14
true / falseTrue / Falsetrue becomes True
nullNonenull becomes None

The Four Key Functions:

FunctionPurposeWorks With
json.loads()Parses a JSON string → Python objectStrings
json.dumps()Converts a Python object → JSON stringStrings
json.load()Reads JSON from a file → Python objectFiles
json.dump()Writes a Python object → JSON fileFiles

Memory Aid: loads/dumps → strings (the ‘s’ stands for string); load/dump → files.

Examples:

import json

# 1. json.loads() — parse JSON string
student_json = '{"name": "Ravi", "age": 21, "marks": 88}'
student = json.loads(student_json)
print(student["name"])    # Ravi
print(student["marks"])   # 88

# 2. json.dumps() — convert Python object to JSON string
student = {"name": "Ravi", "age": 21, "marks": 88}
json_string = json.dumps(student, indent=4)
print(json_string)

# 3. json.dump() — write Python object to JSON file
student = {"name": "Meena", "semester": 5, "skills": ["Python", "SQL"]}
with open("student.json", "w") as file:
    json.dump(student, file, indent=4)

# 4. json.load() — read JSON from file
with open("student.json", "r") as file:
    data = json.load(file)
print(data["skills"])     # ['Python', 'SQL']

Handling JSON Errors:

ErrorReasonSolution
JSONDecodeErrorInvalid JSON syntaxValidate JSON format before parsing
KeyErrorMissing keyUse get() or check if key exists
TypeErrorUnsupported Python objectConvert object to serializable type

Safer key access:

name = data.get("name", "Unknown")
print(name)

Q14. Explain any five RegEx metacharacters and their use in text processing.

Answer:

A Regular Expression (RegEx) is a pattern used to match text. Metacharacters are special symbols that give the pattern its matching power.

Five Important RegEx Metacharacters:

#SymbolMeaningExampleUse in Text Processing
1.Matches any single character except newlinea.c matches abc, axcFlexible matching when one character varies
2^Matches the start of a string^HelloValidate prefixes; check if text begins with a pattern
3$Matches the end of a stringend$Validate suffixes; check if text ends with a pattern
4*Matches zero or more repetitionsab* matches a, ab, abbMatch optional repeated patterns
5+Matches one or more repetitionsab+ matches ab, abbMatch required repeated patterns
6?Matches zero or one repetitioncolou?r matches color, colourOptional characters
7[]Matches one character from a set[aeiou]Character classes (vowels, digits, etc.)
8\dMatches a digit\d+ matches 123Extract numbers from text
9\wMatches a word character\w+Extract words/identifiers
10\sMatches whitespace\s+Match spaces, tabs, newlines

Practical Example:

import re

# 1. Extract all numbers using \d+
text = "My marks are 85 and my attendance is 92"
numbers = re.findall(r"\d+", text)
print(numbers)  # ['85', '92']

# 2. Validate email using ^, $, \w, . and +
email = "student@example.com"
pattern = r"^[\w.-]+@[\w.-]+\.\w+$"
if re.fullmatch(pattern, email):
    print("Valid email")

# 3. Clean multiple spaces using \s+
sentence = "Python    is   easy"
cleaned = re.sub(r"\s+", " ", sentence)
print(cleaned)  # Python is easy

# 4. Optional character using ?
print(re.findall(r"colou?r", "color colour"))  # ['color', 'colour']

# 5. Repetition using *
print(re.findall(r"ab*", "a ab abb abbb"))  # ['a', 'ab', 'abb', 'abbb']

Note: RegEx patterns are usually written as raw strings using r"pattern" to avoid confusion with Python escape characters such as \n and \t.


Q15. Write short notes on try, except, else, finally, and multiple exception handling in Python.

Answer:

An exception is an error that occurs while a program is running. Without exception handling, the program stops immediately. With exception handling, the program can display a meaningful message, recover from the error, or close resources safely.

The Four Blocks:

BlockPurposeWhen It Runs
tryContains code that may raise an exceptionAlways attempted first
exceptHandles a specific exceptionWhen a matching exception occurs
elseRuns if no exception occurredOnly if try succeeds without error
finallyCleanup code (close files, release resources)Always, regardless of exceptions

Basic try-except Structure:

try:
    number = int(input("Enter a number: "))
    print(100 / number)
except ValueError:
    print("Please enter only numbers.")
except ZeroDivisionError:
    print("Cannot divide by zero.")

Multiple Exception Handling:

Multiple except blocks are used when different errors require different responses. Python checks the except blocks from top to bottom and runs the first matching block.

try:
    x = int(input("Enter number: "))
    y = int(input("Enter divisor: "))
    print(x / y)
except ValueError:
    print("Invalid input.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
except Exception as e:
    print("Unexpected error:", e)

else and finally Blocks:

try:
    file = open("data.txt", "r")
    content = file.read()
except FileNotFoundError:
    print("File not found.")
else:
    print("File read successfully.")
finally:
    print("Program finished.")
  • else runs only if no exception occurs.
  • finally runs whether an exception occurs or not. It is commonly used to close files, release resources, or display final messages.

Raising Exceptions:

def set_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    return age

print(set_age(20))    # 20
# print(set_age(-5))  # Raises ValueError

Common Exceptions:

ExceptionWhen It OccursExample
ValueErrorCorrect type but invalid valueint("abc")
ZeroDivisionErrorDivision by zero10 / 0
FileNotFoundErrorFile does not existopen("missing.txt")
KeyErrorDictionary key is missingstudent["age"]
IndexErrorList index out of rangeitems[10]
TypeErrorOperation on incompatible types"5" + 2

Best Practice: Avoid using a bare except: block because it catches all errors and can hide programming mistakes. Catch specific exceptions whenever possible.


Q16. Explain different file opening modes in Python with examples.

Answer:

File handling allows a program to store data permanently and read data from external sources. The open() function is used to open a file and returns a file object.

File Opening Modes:

ModeMeaningUse CaseExample
rRead mode. File must existRead an existing text fileopen("data.txt", "r")
wWrite mode. Creates or overwrites fileSave new outputopen("output.txt", "w")
aAppend mode. Adds content at the endAdd log messagesopen("log.txt", "a")
xCreate mode. Fails if file existsCreate a new file safelyopen("new.txt", "x")
bBinary modeRead images, audio, or binary dataopen("image.png", "rb")
tText mode (default)Read normal text filesopen("data.txt", "rt")
+Read and write modeUpdate file contentopen("data.txt", "r+")

Examples:

# 1. Read mode (r)
with open("students.txt", "r") as file:
    print(file.read())          # Read entire file

# 2. Write mode (w) — overwrites existing content
with open("output.txt", "w") as file:
    file.write("First line\n")
    file.write("Second line\n")

# 3. Append mode (a) — adds to end
with open("output.txt", "a") as file:
    file.write("Appended line\n")

# 4. Create mode (x) — fails if file exists
try:
    with open("newfile.txt", "x") as file:
        file.write("Created safely\n")
except FileExistsError:
    print("File already exists.")

# 5. Binary mode (b) — read image
with open("photo.jpg", "rb") as file:
    data = file.read()

# 6. Read and write mode (+)
with open("data.txt", "r+") as file:
    content = file.read()
    file.write("\nNew line appended.")

Reading Methods:

with open("students.txt", "r") as file:
    print(file.read())          # Read entire file
    print(file.readline())      # Read one line
    for line in file:           # Read line by line
        print(line.strip())

File Handling with Exceptions:

try:
    with open("marks.txt", "r") as file:
        marks = file.read()
        print(marks)
except FileNotFoundError:
    print("The file marks.txt was not found.")

Important Concepts:

ConceptExplanation
Current working directoryFolder from which the Python program is running
Absolute pathFull path from the root of the system
Relative pathPath relative to the current working directory
EncodingRule to convert text into bytes and vice versa
BufferingTemporary storage used while reading/writing

Best Practice: Always use the with statement because it automatically closes the file, even if an exception occurs.


PART C — LONG ANSWER / ESSAY QUESTIONS (10 Marks Each)


Q17. Discuss Python modules in detail. Include creating user-defined modules, using built-in modules, module aliases, variables in modules, and the dir() function.

Answer:

1. Introduction to Python Modules

A module is a Python file (with .py extension) that contains functions, classes, variables, and executable statements. The file name becomes the module name without the extension. For example, calculator.py becomes the module calculator.

Modules allow programmers to organize code logically. A large program can be divided into smaller files, where each file handles one responsibility. This makes the program easier to read, test, debug, and maintain.

Key Insight: A module is not a separate programming language. It is simply a Python file that can be reused by importing it into another Python file.

2. Module, Package, and Library

ConceptMeaningSimple Example
ModuleOne Python filemath_tools.py
PackageA folder grouping related modulesdata_utils/ with cleaning.py
LibraryA collection of modules and packagesNumPy, Pandas

Hierarchy: Library ⊃ Package ⊃ Module

3. Creating User-Defined Modules

Steps:

  1. Create a new Python file with a meaningful name (e.g., mymath.py).
  2. Define functions, variables, or classes inside the file.
  3. Save the file in the same folder as the program that will use it.
  4. Use the import statement in another Python file.
  5. Access module members using dot notation.

Example:

# File name: calculator_tools.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

PI = 3.14159
# File name: main.py
import calculator_tools

print(calculator_tools.add(10, 5))       # 15
print(calculator_tools.subtract(10, 5))  # 5
print(calculator_tools.PI)               # 3.14159

Best Practices:

  • Keep each module focused on one main purpose.
  • Use meaningful function and variable names.
  • Avoid writing too much executable code directly at module level.
  • Add comments or docstrings.
  • Test the module independently before integration.

4. Module Naming Rules

RuleCorrect ExampleIncorrect Example
Use lowercase lettersstudent_records.pyStudentRecords.py
Use underscoresfile_utils.pyfile-utils.py
Do not begin with a numbermodule3_notes.py3module.py
Avoid spacesdata_cleaning.pydata cleaning.py
Avoid built-in module namesmy_math_tools.pymath.py

5. Module Aliases

Python allows an imported module to be given a shorter name using the as keyword. This does not rename the original file; it only creates an alias inside the current program.

import math as m
print(m.sqrt(25))   # 5.0
print(m.pi)         # 3.14159...

import random as rd
number = rd.randint(1, 10)
print(number)

Common Aliases:

  • import numpy as np
  • import pandas as pd
  • import matplotlib.pyplot as plt

Important: Do not create files named math.py, random.py, json.py, or re.py in your project folder. These names can hide the original built-in modules and cause confusing errors.

6. Variables in Modules

A module can store variables just like a normal Python program. These variables can be accessed after importing the module. Module-level variables are useful for constants, configuration values, version numbers, and shared settings.

# File name: college_info.py
college_name = "ABC Institute"
course = "Python Programming"
semester = 5
# File name: main.py
import college_info

print(college_info.college_name)  # ABC Institute
print(college_info.course)        # Python Programming
print(college_info.semester)      # 5

7. Built-in Modules

Python includes many ready-to-use modules in its standard library.

ModulePurposeExample Use
mathMathematical functions and constantssqrt(), ceil(), pi
randomRandom number generationrandint(), choice(), shuffle()
datetimeDates and timesdate.today(), datetime.now()
osOperating system interactionlistdir(), mkdir()
sysPython interpreter informationsys.version, sys.path
jsonJSON parsing and conversionloads(), dumps(), load(), dump()
reRegular expression operationssearch(), findall(), sub()
statisticsBasic statisticsmean(), median(), mode()

Examples:

import math
print(math.sqrt(64))  # 8.0

import random
print(random.choice(["red", "blue", "green"]))

from datetime import date
print(date.today())

8. The dir() Function

The dir() function returns a list of names available inside an object or module. It is useful for exploring what functions, classes, constants, and attributes are provided by a module.

import math
print(dir(math))
print(math.sqrt(16))
Use of dir()Meaning
dir(math)Displays names available in the math module
dir(str)Displays methods available for string objects
dir()Displays names available in the current scope

9. Import Styles

Import StyleSyntaxWhen to Use
Import full moduleimport mathWhen many functions are required
Import with aliasimport math as mWhen a shorter name improves readability
Import one namefrom math import sqrtWhen only one function is needed
Import multiple namesfrom math import sqrt, piWhen a few names are needed
Import all namesfrom math import *Generally avoided (name conflicts)

10. The __name__ Variable

When a Python file is run directly, __name__ is set to "__main__". When imported as a module, __name__ becomes the module name. This allows a file to contain test code that runs only when executed directly.

# File name: greetings.py
def welcome(name):
    return "Welcome, " + name

if __name__ == "__main__":
    print(welcome("Student"))

Why it matters: Prevents test code from running automatically when a module is imported into another program.

11. The Python Module Workflow

Create → Test → Package → Distribute → Import & Reuse
   ↑                                          │
   └──────────── Iterate & Improve ───────────┘
  1. Create Module: Write functions, classes, variables.
  2. Write & Test: Test with different inputs.
  3. Package Module: Organize with __init__.py and metadata.
  4. Distribute: Share through PyPI or private repository.
  5. Import & Reuse: Import into programs; install via pip.

Iterate & Improve: Fix bugs, optimize, add features, and redistribute.


Answer:

1. Introduction to JSON

JSON (JavaScript Object Notation) is a lightweight text format used for storing and exchanging structured data. It is widely used in:

  • Web applications
  • APIs
  • Configuration files
  • Databases
  • Data transfer between systems

2. JSON Data Types and Python Mapping

JSON TypePython EquivalentExample
objectdict{"name": "Amit"}
arraylist[10, 20, 30]
stringstr"Python"
numberint or float25 or 3.14
true / falseTrue / Falsetrue becomes True
nullNonenull becomes None

3. The json Module

Python provides the built-in json module for working with JSON data.

FunctionPurpose
json.loads()Parses a JSON string → Python object
json.dumps()Converts a Python object → JSON string
json.load()Reads JSON data from a file → Python object
json.dump()Writes a Python object → JSON file

4. Parsing JSON Strings

Parsing means reading JSON text and converting it into Python data structures.

import json

student_json = '{"name": "Ravi", "age": 21, "marks": 88}'
student = json.loads(student_json)

print(student["name"])    # Ravi
print(student["marks"])   # 88

5. Parsing Nested JSON

import json

data = '''
{
    "student": {
        "name": "Meena",
        "age": 20,
        "subjects": ["Python", "DBMS", "AI"]
    }
}
'''

obj = json.loads(data)
print(obj["student"]["name"])         # Meena
print(obj["student"]["subjects"][0])  # Python

6. Converting Python Objects to JSON

import json

student = {
    "name": "Ravi",
    "age": 21,
    "marks": 88
}

json_string = json.dumps(student, indent=4)
print(json_string)

Output:

{
    "name": "Ravi",
    "age": 21,
    "marks": 88
}

7. Reading JSON Files

import json

with open("student.json", "r") as file:
    data = json.load(file)

print(data["skills"])

8. Writing JSON Files

import json

student = {
    "name": "Meena",
    "semester": 5,
    "skills": ["Python", "SQL"]
}

with open("student.json", "w") as file:
    json.dump(student, file, indent=4)

Note: The indent=4 parameter produces readable, formatted JSON output.

9. Handling JSON Errors

Common JSON ErrorReasonSolution
JSONDecodeErrorInvalid JSON syntax (missing quotes, extra comma)Validate JSON format before parsing
KeyErrorTrying to access a key that does not existUse get() or check if key exists
TypeErrorTrying to serialize an unsupported Python objectConvert object to a serializable type

Safer Key Access:

name = data.get("name", "Unknown")
print(name)

10. Complete Example with Error Handling

import json

try:
    with open("students.json", "r", encoding="utf-8") as file:
        students = json.load(file)
    print(f"Loaded{len(students)} records.")
except FileNotFoundError:
    print("Input JSON file not found.")
except json.JSONDecodeError:
    print("Invalid JSON format.")
except Exception as error:
    print("Unexpected error:", error)

11. Applications of JSON

  • APIs: REST APIs exchange data in JSON format.
  • Configuration: Many tools use JSON config files.
  • Data Storage: NoSQL databases like MongoDB store JSON-like documents.
  • Web Development: JavaScript natively handles JSON.

Q19. Describe Regular Expressions in Python. Explain the re module functions search(), match(), fullmatch(), findall(), split(), sub(), and compile() with examples.

Answer:

1. Introduction to Regular Expressions

A Regular Expression (RegEx) is a pattern used to match text. It is useful for:

  • Validating input (emails, phone numbers)
  • Extracting values from text
  • Searching documents
  • Cleaning text
  • Replacing unwanted content

2. RegEx Workflow

Define Pattern → Compile → Search/Match → Process/Extract → Validate/Output

3. RegEx Metacharacters

SymbolMeaningExample
.Any single character except newlinea.c matches abc, axc
^Start of string^Hello
$End of stringend$
*Zero or more repetitionsab* matches a, ab, abb
+One or more repetitionsab+ matches ab, abb
?Zero or one repetitioncolou?r matches color, colour
[]One character from a set[aeiou]
\dDigit\d+ matches 123
\wWord character\w+
\sWhitespace\s+

4. The re Module Functions

(a) re.search(pattern, text)

Searches anywhere in the string and returns the first match.

import re
text = "Python is easy"
match = re.search(r"is", text)
if match:
    print("Found at position:", match.start())  # Found at position: 7

(b) re.match(pattern, text)

Checks for a match only at the beginning of the string.

import re
print(re.match(r"Python", "Python is easy"))  # Match
print(re.match(r"easy", "Python is easy"))    # None (not at start)

(c) re.fullmatch(pattern, text)

Checks whether the entire string matches the pattern.

import re
email = "student@example.com"
pattern = r"^[\w.-]+@[\w.-]+\.\w+$"
if re.fullmatch(pattern, email):
    print("Valid email")  # Valid email

(d) re.findall(pattern, text)

Returns all matching substrings as a list.

import re
text = "My marks are 85 and my attendance is 92"
numbers = re.findall(r"\d+", text)
print(numbers)  # ['85', '92']

(e) re.split(pattern, text)

Splits a string based on the pattern.

import re
text = "apple,banana,orange"
fruits = re.split(r",", text)
print(fruits)  # ['apple', 'banana', 'orange']

(f) re.sub(pattern, replacement, text)

Replaces matching text with new text.

import re
sentence = "Python    is   easy"
cleaned = re.sub(r"\s+", " ", sentence)
print(cleaned)  # Python is easy

(g) re.compile(pattern)

Compiles a pattern for repeated use (improves performance).

import re
pattern = re.compile(r"\d+")
print(pattern.findall("a1b2c3"))  # ['1', '2', '3']
print(pattern.findall("x10y20"))  # ['10', '20']

5. Practical Examples

Example 1: Validate Email

import re
email = "student@example.com"
pattern = r"^[\w.-]+@[\w.-]+\.\w+$"
if re.fullmatch(pattern, email):
    print("Valid email")
else:
    print("Invalid email")

Example 2: Extract Phone Numbers

import re
text = "Call 123-456-7890 or 987-654-3210"
phones = re.findall(r"\d{3}-\d{3}-\d{4}", text)
print(phones)  # ['123-456-7890', '987-654-3210']

Example 3: Clean Whitespace

import re
messy = "Too     many    spaces"
clean = re.sub(r"\s+", " ", messy)
print(clean)  # Too many spaces

Example 4: Split by Multiple Delimiters

import re
data = "apple;banana,orange|grape"
items = re.split(r"[;,|]", data)
print(items)  # ['apple', 'banana', 'orange', 'grape']

6. Raw Strings

RegEx patterns are usually written as raw strings using r"pattern". This avoids confusion with Python escape characters such as \n and \t.

# Correct
pattern = r"\d+"

# Incorrect (may cause issues)
pattern = "\d+"

7. Applications of RegEx

  • Input validation: Emails, phone numbers, passwords.
  • Text extraction: Parsing logs, scraping data.
  • Search and replace: Cleaning data.
  • Tokenization: Splitting text into words/tokens.
  • Pattern matching: Finding specific sequences.

Q20. Explain exception handling and file handling together by writing a program that reads a file, processes data, handles missing files, and writes output safely.

Answer:

1. Introduction

Exception handling prevents sudden program termination and provides user-friendly error reporting. File handling allows programs to read and write permanent data safely. Combining both ensures robust, reliable applications.

2. The Safe File Handling Workflow

Open File → Read/Write → Process Data → Close Safely → Handle Errors

3. Key Concepts

Exception Handling:

BlockPurpose
tryCode that may raise an exception
exceptHandles specific exceptions
elseRuns if no exception occurs
finallyAlways runs (cleanup)

File Modes:

ModeMeaning
rRead (file must exist)
wWrite (creates/overwrites)
aAppend (adds at end)
xCreate (fails if exists)

4. Complete Program

Scenario: Read student marks from a file, compute average, handle missing files, and write results safely.

def process_marks(input_file, output_file):
    """
    Read marks from input_file, compute average,
    and write results to output_file.
    Handles missing files and invalid data.
    """
    try:
        # Step 1: Open and read the input file
        with open(input_file, "r", encoding="utf-8") as file:
            lines = file.readlines()

        # Step 2: Process data
        results = []
        for line in lines:
            parts = line.strip().split(",")
            if len(parts) != 2:
                print(f"Skipping invalid line:{line.strip()}")
                continue

            name, marks_str = parts
            try:
                marks = float(marks_str)
                results.append((name, marks))
            except ValueError:
                print(f"Invalid marks for{name}:{marks_str}")

        # Step 3: Compute average
        if results:
            total = sum(m for _, m in results)
            average = total / len(results)
        else:
            average = 0
            print("No valid records found.")

        # Step 4: Write output safely
        with open(output_file, "w", encoding="utf-8") as file:
            file.write(f"Total students:{len(results)}\n")
            file.write(f"Average marks:{average:.2f}\n")
            file.write("\nDetailed Results:\n")
            for name, marks in results:
                file.write(f"{name}:{marks}\n")

        print(f"Results saved to{output_file}")

    except FileNotFoundError:
        print(f"Error: '{input_file}' not found.")
    except PermissionError:
        print(f"Error: Permission denied for '{input_file}'.")
    except Exception as error:
        print("Unexpected error:", error)
    finally:
        print("Processing finished.")

# Usage
process_marks("marks.txt", "results.txt")

Sample Input (marks.txt):

Ravi,85
Meena,92
Arjun,invalid
Priya,78

Sample Output (results.txt):

Total students: 3
Average marks: 85.00

Detailed Results:
Ravi: 85.0
Meena: 92.0
Priya: 78.0

Console Output:

Invalid marks for Arjun: invalid
Results saved to results.txt
Processing finished.

5. Explanation of Concepts Used

ConceptWhere It Appears
try-exceptWraps file operations and data processing
FileNotFoundErrorHandles missing input file
PermissionErrorHandles permission issues
ValueErrorHandles invalid marks conversion
with open()Auto-closes files safely
encoding="utf-8"Supports multilingual text
finallyEnsures cleanup message runs
Nested try-exceptHandles per-line errors without crashing

6. Best Practices

  1. Always use with for file operations — auto-closes files.
  2. Catch specific exceptions — avoid bare except:.
  3. Use encoding="utf-8" for text files.
  4. Validate data before processing.
  5. Use finally for cleanup tasks.
  6. Log errors instead of silent failures.
  7. Test with edge cases — empty files, missing files, invalid data.

7. Real-World Applications

  • Log analysis: Read server logs, extract errors, write reports.
  • Data cleaning: Read CSV/JSON, validate, write cleaned data.
  • ETL pipelines: Extract, transform, load data safely.
  • Configuration management: Read settings, validate, apply.

PART D — ANALYTICAL / CASE-BASED QUESTIONS


Q21 (Case Study). A college stores student data in a JSON file. Each record contains name, register number, email, and marks. Design a Python program that reads the JSON file, validates email addresses using RegEx, handles file and JSON errors, and saves only valid records into a new file. Explain each step.

Answer:

1. Problem Statement

The college needs a program that:

  1. Reads student data from a JSON file.
  2. Validates email addresses using RegEx.
  3. Handles file and JSON errors.
  4. Saves only valid records into a new JSON file.

2. Design Approach

Step 1: Import required modules (json, re). Step 2: Define the email validation pattern. Step 3: Read the JSON file with error handling. Step 4: Validate each record’s email. Step 5: Filter valid records. Step 6: Write valid records to a new JSON file. Step 7: Handle all exceptions gracefully.

3. Complete Program

import json
import re

# Step 1: Define email validation pattern
EMAIL_PATTERN = r"^[\w.-]+@[\w.-]+\.\w+$"

def is_valid_email(email):
    """Check if email matches the pattern."""
    if not email:
        return False
    return re.fullmatch(EMAIL_PATTERN, email) is not None

def validate_student(student):
    """Check if a student record has all required fields with valid email."""
    required_fields = ["name", "register_number", "email", "marks"]
    for field in required_fields:
        if field not in student:
            return False
    return is_valid_email(student.get("email", ""))

def process_student_records(input_file, output_file):
    """Read, validate, and save student records."""
    try:
        # Step 2: Read JSON file
        with open(input_file, "r", encoding="utf-8") as file:
            students = json.load(file)

        if not isinstance(students, list):
            print("Error: JSON root must be a list of students.")
            return

        # Step 3: Validate and filter records
        valid_students = []
        invalid_count = 0

        for student in students:
            if validate_student(student):
                valid_students.append(student)
            else:
                invalid_count += 1
                print(f"Invalid record skipped:{student.get('name', 'Unknown')}")

        # Step 4: Write valid records to new file
        with open(output_file, "w", encoding="utf-8") as file:
            json.dump(valid_students, file, indent=4)

        # Step 5: Summary
        print(f"\nProcessing complete.")
        print(f"Total records:{len(students)}")
        print(f"Valid records:{len(valid_students)}")
        print(f"Invalid records:{invalid_count}")
        print(f"Saved to:{output_file}")

    except FileNotFoundError:
        print(f"Error: Input file '{input_file}' not found.")
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON format -{e}")
    except PermissionError:
        print(f"Error: Permission denied for '{input_file}' or '{output_file}'.")
    except Exception as error:
        print(f"Unexpected error:{error}")

# Usage
process_student_records("students.json", "valid_students.json")

4. Sample Input (students.json)

[
    {
        "name": "Ravi",
        "register_number": "R001",
        "email": "ravi@college.edu",
        "marks": 85
    },
    {
        "name": "Meena",
        "register_number": "R002",
        "email": "invalid-email",
        "marks": 92
    },
    {
        "name": "Arjun",
        "register_number": "R003",
        "email": "arjun@college.edu",
        "marks": 78
    },
    {
        "name": "Priya",
        "register_number": "R004",
        "email": "priya@college",
        "marks": 88
    }
]

5. Sample Output

Console:

Invalid record skipped: Meena
Invalid record skipped: Priya

Processing complete.
Total records: 4
Valid records: 2
Invalid records: 2
Saved to: valid_students.json

Output File (valid_students.json):

[
    {
        "name": "Ravi",
        "register_number": "R001",
        "email": "ravi@college.edu",
        "marks": 85
    },
    {
        "name": "Arjun",
        "register_number": "R003",
        "email": "arjun@college.edu",
        "marks": 78
    }
]

6. Step-by-Step Explanation

StepActionCode
1Import modulesimport json, import re
2Define email patternEMAIL_PATTERN = r"^[\w.-]+@[\w.-]+\.\w+$"
3Validate emailre.fullmatch(EMAIL_PATTERN, email)
4Check required fieldsfor field in required_fields
5Read JSON filejson.load(file)
6Filter valid recordsList comprehension / loop
7Write output filejson.dump(valid_students, file, indent=4)
8Handle errorsMultiple except blocks

7. Error Handling Coverage

ErrorHandling
Missing fileexcept FileNotFoundError
Invalid JSONexcept json.JSONDecodeError
Permission issueexcept PermissionError
Missing fieldsvalidate_student() checks
Invalid emailis_valid_email() checks
Unexpected errorsexcept Exception

8. Enhancements (Optional)

  • Phone validation: Add a phone regex pattern.
  • Marks validation: Ensure marks are between 0 and 100.
  • Duplicate detection: Check for duplicate register numbers.
  • Logging: Write errors to a log file instead of console.
  • CSV output: Save results as CSV for Excel compatibility.

Q22 (Compare and Analyse). Compare modules, JSON processing, RegEx, exception handling, and file handling in a table. Explain how these concepts can be combined in a real-world Python application such as log analysis or student record management.

Answer:

1. Comparison Table

ConceptPurposeKey Functions/SyntaxCommon Use CasesOutput
ModulesOrganize and reuse codeimport, from ... import, as, dir()Code reuse, built-in libraries, package organizationReusable .py files
JSON ProcessingExchange structured datajson.loads(), json.dumps(), json.load(), json.dump()APIs, config files, data storagePython objects ↔︎ JSON text/files
RegExPattern matching in textre.search(), re.findall(), re.sub(), re.fullmatch()Validation, extraction, cleaningMatched patterns or modified text
Exception HandlingHandle runtime errorstry, except, else, finally, raiseError recovery, resource cleanupGraceful error messages
File HandlingRead/write persistent dataopen(), read(), write(), with, modes (r, w, a)Data storage, logs, configurationFile objects, persistent data

2. How These Concepts Work Together

ConceptRole in ApplicationInteracts With
ModulesProvide functionality (json, re, os)All other concepts
File HandlingRead input and write outputJSON, RegEx, Exceptions
JSONParse/store structured dataFile handling, Exceptions
RegExValidate/clean text dataJSON, File handling
Exception HandlingProtect all operationsAll other concepts

3. Real-World Application 1: Log Analysis

Scenario: A system administrator wants to analyze server logs, extract error messages, count occurrences, and generate a report.

Program:

import re
import json
from collections import Counter

def analyze_logs(log_file, output_file):
    """Analyze log file, extract errors, and save report."""
    try:
        # Step 1: Read log file
        with open(log_file, "r", encoding="utf-8") as file:
            lines = file.readlines()

        # Step 2: Extract error patterns using RegEx
        error_pattern = r"ERROR:\s+(.+)"
        errors = []
        for line in lines:
            match = re.search(error_pattern, line)
            if match:
                errors.append(match.group(1).strip())

        # Step 3: Count occurrences
        error_counts = Counter(errors)

        # Step 4: Build report
        report = {
            "total_lines": len(lines),
            "total_errors": len(errors),
            "unique_errors": len(error_counts),
            "top_errors": error_counts.most_common(5)
        }

        # Step 5: Write JSON report
        with open(output_file, "w", encoding="utf-8") as file:
            json.dump(report, file, indent=4)

        print(f"Report saved to{output_file}")

    except FileNotFoundError:
        print(f"Log file '{log_file}' not found.")
    except Exception as error:
        print(f"Unexpected error:{error}")

# Usage
analyze_logs("server.log", "error_report.json")

Concepts Used:

  • File handling: Read log file, write JSON report.
  • RegEx: Extract error messages (ERROR:\s+(.+)).
  • JSON: Structure the report.
  • Exception handling: Handle missing file.
  • Modules: re, json, collections.

4. Real-World Application 2: Student Record Management

Scenario: A college wants to read student records from JSON, validate emails and phone numbers, and save valid records.

Program:

import json
import re

EMAIL_PATTERN = r"^[\w.-]+@[\w.-]+\.\w+$"
PHONE_PATTERN = r"^\d{3}-\d{3}-\d{4}$"

def validate_student(student):
    """Validate email and phone."""
    email = student.get("email", "")
    phone = student.get("phone", "")
    return (re.fullmatch(EMAIL_PATTERN, email) and
            re.fullmatch(PHONE_PATTERN, phone))

def manage_students(input_file, output_file):
    """Read, validate, and save student records."""
    try:
        with open(input_file, "r", encoding="utf-8") as file:
            students = json.load(file)

        valid = [s for s in students if validate_student(s)]

        with open(output_file, "w", encoding="utf-8") as file:
            json.dump(valid, file, indent=4)

        print(f"Saved{len(valid)} valid records.")

    except FileNotFoundError:
        print("Input file not found.")
    except json.JSONDecodeError:
        print("Invalid JSON format.")
    except Exception as error:
        print(f"Unexpected error:{error}")

# Usage
manage_students("students.json", "valid_students.json")

Concepts Used:

  • Modules: json, re.
  • File handling: Read input JSON, write output JSON.
  • JSON: Parse and serialize records.
  • RegEx: Validate email and phone.
  • Exception handling: Handle missing file and invalid JSON.

5. Real-World Application 3: API Data Processing

Scenario: Fetch data from an API, validate responses, and store in a file.

import json
import re

def process_api_response(response_text, output_file):
    """Parse API response, validate, and save."""
    try:
        data = json.loads(response_text)
        valid_entries = []

        for entry in data.get("results", []):
            email = entry.get("email", "")
            if re.fullmatch(r"^[\w.-]+@[\w.-]+\.\w+$", email):
                valid_entries.append(entry)

        with open(output_file, "w", encoding="utf-8") as file:
            json.dump(valid_entries, file, indent=4)

        print(f"Saved{len(valid_entries)} valid entries.")

    except json.JSONDecodeError:
        print("Invalid JSON response.")
    except Exception as error:
        print(f"Unexpected error:{error}")

6. Benefits of Combining These Concepts

BenefitDescription
RobustnessException handling prevents crashes
Data IntegrityRegEx validates input
InteroperabilityJSON enables data exchange
PersistenceFile handling stores data permanently
ReusabilityModules organize code
MaintainabilityClean separation of concerns
ScalabilityEasy to extend for larger datasets

7. Summary

The five concepts form a complete data processing pipeline:

Modules (tools) → File Handling (I/O) → JSON (structure) → RegEx (validation) → Exception Handling (safety)

Real-World Applications:

  • Log analysis: Parse logs, extract errors, generate reports.
  • Student management: Validate records, filter, save.
  • API processing: Fetch, validate, store data.
  • ETL pipelines: Extract, transform, load data.
  • Configuration management: Read, validate, apply settings.

Best Practices:

  1. Use with for file operations.
  2. Catch specific exceptions.
  3. Validate data with RegEx.
  4. Use JSON for structured data.
  5. Organize code into modules.
  6. Test edge cases (empty files, invalid data, missing keys).

On this page

PART A — MULTIPLE CHOICE QUESTIONS (1 Mark Each)PART B — SHORT ANSWER QUESTIONS (5 Marks Each)Q11. Define a Python module. Explain any four advantages of using modules in Python programs.Q12. Explain the difference between import module, import module as alias, and from module import name with examples.Q13. What is JSON? Explain json.loads(), json.dumps(), json.load(), and json.dump() with suitable examples.Q14. Explain any five RegEx metacharacters and their use in text processing.Q15. Write short notes on try, except, else, finally, and multiple exception handling in Python.Q16. Explain different file opening modes in Python with examples.PART C — LONG ANSWER / ESSAY QUESTIONS (10 Marks Each)Q17. Discuss Python modules in detail. Include creating user-defined modules, using built-in modules, module aliases, variables in modules, and the dir() function.1. Introduction to Python Modules2. Module, Package, and Library3. Creating User-Defined Modules4. Module Naming Rules5. Module Aliases6. Variables in Modules7. Built-in Modules8. The dir() Function9. Import Styles10. The __name__ Variable11. The Python Module WorkflowQ18. Explain JSON handling in Python. Describe parsing JSON strings, reading JSON files, converting Python objects to JSON, writing JSON files, and handling JSON-related errors.1. Introduction to JSON2. JSON Data Types and Python Mapping3. The json Module4. Parsing JSON Strings5. Parsing Nested JSON6. Converting Python Objects to JSON7. Reading JSON Files8. Writing JSON Files9. Handling JSON Errors10. Complete Example with Error Handling11. Applications of JSONQ19. Describe Regular Expressions in Python. Explain the re module functions search(), match(), fullmatch(), findall(), split(), sub(), and compile() with examples.1. Introduction to Regular Expressions2. RegEx Workflow3. RegEx Metacharacters4. The re Module Functions(a) re.search(pattern, text)(b) re.match(pattern, text)(c) re.fullmatch(pattern, text)(d) re.findall(pattern, text)(e) re.split(pattern, text)(f) re.sub(pattern, replacement, text)(g) re.compile(pattern)5. Practical Examples6. Raw Strings7. Applications of RegExQ20. Explain exception handling and file handling together by writing a program that reads a file, processes data, handles missing files, and writes output safely.1. Introduction2. The Safe File Handling Workflow3. Key Concepts4. Complete Program5. Explanation of Concepts Used6. Best Practices7. Real-World ApplicationsPART D — ANALYTICAL / CASE-BASED QUESTIONSQ21 (Case Study). A college stores student data in a JSON file. Each record contains name, register number, email, and marks. Design a Python program that reads the JSON file, validates email addresses using RegEx, handles file and JSON errors, and saves only valid records into a new file. Explain each step.1. Problem Statement2. Design Approach3. Complete Program4. Sample Input (students.json)5. Sample Output6. Step-by-Step Explanation7. Error Handling Coverage8. Enhancements (Optional)Q22 (Compare and Analyse). Compare modules, JSON processing, RegEx, exception handling, and file handling in a table. Explain how these concepts can be combined in a real-world Python application such as log analysis or student record management.1. Comparison Table2. How These Concepts Work Together3. Real-World Application 1: Log Analysis4. Real-World Application 2: Student Record Management5. Real-World Application 3: API Data Processing6. Benefits of Combining These Concepts7. Summary