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?
- txt
- py
- json
- 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?
- include
- import
- module
- 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?
- Delete a module
- Rename the Python file permanently
- Create an alias for the imported module
- 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?
- list()
- names()
- dir()
- 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?
- json.dumps()
- json.loads()
- json.dump()
- 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"]) # RaviQ6. Which json function writes a Python object into a JSON file?
- json.write()
- json.save()
- json.dump()
- 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?
- regex
- re
- string
- 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?
- re.sub()
- re.replace()
- re.change()
- 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 easyQ9. Which exception occurs when a program tries to divide by zero?
- ValueError
- TypeError
- ZeroDivisionError
- 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?
- r
- w
- a
- 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:
| # | Advantage | Explanation | Example |
|---|---|---|---|
| 1 | Code Reuse | Write once and use in many programs, avoiding duplication | Use the same tax calculation function in multiple billing programs |
| 2 | Organisation | Separate a large program into smaller logical files, improving readability | Keep database code, validation code, and report code in separate modules |
| 3 | Maintainability | Changes can be made in one module without rewriting the full application | Update one email-sending module used across the project |
| 4 | Testing | Individual modules can be tested independently before integration | Test 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 Style | Syntax | When to Use | Example |
|---|---|---|---|
| Import full module | import math | When many functions from the module are required | math.sqrt(81) |
| Import with alias | import math as m | When a shorter name improves readability | m.sqrt(81) |
| Import one name | from math import sqrt | When only one function or variable is needed | sqrt(81) |
| Import multiple names | from math import sqrt, pi | When a few selected names are needed | sqrt(81), pi |
| Import all names | from math import * | Generally avoided because it can create name conflicts | sqrt(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 viamodule.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 Type | Python Equivalent | Example |
|---|---|---|
| object | dict | {"name": "Amit"} |
| array | list | [10, 20, 30] |
| string | str | "Python" |
| number | int or float | 25 or 3.14 |
| true / false | True / False | true becomes True |
| null | None | null becomes None |
The Four Key Functions:
| Function | Purpose | Works With |
|---|---|---|
json.loads() | Parses a JSON string → Python object | Strings |
json.dumps() | Converts a Python object → JSON string | Strings |
json.load() | Reads JSON from a file → Python object | Files |
json.dump() | Writes a Python object → JSON file | Files |
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:
| Error | Reason | Solution |
|---|---|---|
JSONDecodeError | Invalid JSON syntax | Validate JSON format before parsing |
KeyError | Missing key | Use get() or check if key exists |
TypeError | Unsupported Python object | Convert 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:
| # | Symbol | Meaning | Example | Use in Text Processing |
|---|---|---|---|---|
| 1 | . | Matches any single character except newline | a.c matches abc, axc | Flexible matching when one character varies |
| 2 | ^ | Matches the start of a string | ^Hello | Validate prefixes; check if text begins with a pattern |
| 3 | $ | Matches the end of a string | end$ | Validate suffixes; check if text ends with a pattern |
| 4 | * | Matches zero or more repetitions | ab* matches a, ab, abb | Match optional repeated patterns |
| 5 | + | Matches one or more repetitions | ab+ matches ab, abb | Match required repeated patterns |
| 6 | ? | Matches zero or one repetition | colou?r matches color, colour | Optional characters |
| 7 | [] | Matches one character from a set | [aeiou] | Character classes (vowels, digits, etc.) |
| 8 | \d | Matches a digit | \d+ matches 123 | Extract numbers from text |
| 9 | \w | Matches a word character | \w+ | Extract words/identifiers |
| 10 | \s | Matches 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:
| Block | Purpose | When It Runs |
|---|---|---|
try | Contains code that may raise an exception | Always attempted first |
except | Handles a specific exception | When a matching exception occurs |
else | Runs if no exception occurred | Only if try succeeds without error |
finally | Cleanup 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.")elseruns only if no exception occurs.finallyruns 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 ValueErrorCommon Exceptions:
| Exception | When It Occurs | Example |
|---|---|---|
ValueError | Correct type but invalid value | int("abc") |
ZeroDivisionError | Division by zero | 10 / 0 |
FileNotFoundError | File does not exist | open("missing.txt") |
KeyError | Dictionary key is missing | student["age"] |
IndexError | List index out of range | items[10] |
TypeError | Operation 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:
| Mode | Meaning | Use Case | Example |
|---|---|---|---|
r | Read mode. File must exist | Read an existing text file | open("data.txt", "r") |
w | Write mode. Creates or overwrites file | Save new output | open("output.txt", "w") |
a | Append mode. Adds content at the end | Add log messages | open("log.txt", "a") |
x | Create mode. Fails if file exists | Create a new file safely | open("new.txt", "x") |
b | Binary mode | Read images, audio, or binary data | open("image.png", "rb") |
t | Text mode (default) | Read normal text files | open("data.txt", "rt") |
+ | Read and write mode | Update file content | open("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:
| Concept | Explanation |
|---|---|
| Current working directory | Folder from which the Python program is running |
| Absolute path | Full path from the root of the system |
| Relative path | Path relative to the current working directory |
| Encoding | Rule to convert text into bytes and vice versa |
| Buffering | Temporary 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
| Concept | Meaning | Simple Example |
|---|---|---|
| Module | One Python file | math_tools.py |
| Package | A folder grouping related modules | data_utils/ with cleaning.py |
| Library | A collection of modules and packages | NumPy, Pandas |
Hierarchy: Library ⊃ Package ⊃ Module
3. Creating User-Defined Modules
Steps:
- Create a new Python file with a meaningful name (e.g.,
mymath.py). - Define functions, variables, or classes inside the file.
- Save the file in the same folder as the program that will use it.
- Use the
importstatement in another Python file. - 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.14159Best 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
| Rule | Correct Example | Incorrect Example |
|---|---|---|
| Use lowercase letters | student_records.py | StudentRecords.py |
| Use underscores | file_utils.py | file-utils.py |
| Do not begin with a number | module3_notes.py | 3module.py |
| Avoid spaces | data_cleaning.py | data cleaning.py |
| Avoid built-in module names | my_math_tools.py | math.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 npimport pandas as pdimport 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) # 57. Built-in Modules
Python includes many ready-to-use modules in its standard library.
| Module | Purpose | Example Use |
|---|---|---|
math | Mathematical functions and constants | sqrt(), ceil(), pi |
random | Random number generation | randint(), choice(), shuffle() |
datetime | Dates and times | date.today(), datetime.now() |
os | Operating system interaction | listdir(), mkdir() |
sys | Python interpreter information | sys.version, sys.path |
json | JSON parsing and conversion | loads(), dumps(), load(), dump() |
re | Regular expression operations | search(), findall(), sub() |
statistics | Basic statistics | mean(), 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 Style | Syntax | When to Use |
|---|---|---|
| Import full module | import math | When many functions are required |
| Import with alias | import math as m | When a shorter name improves readability |
| Import one name | from math import sqrt | When only one function is needed |
| Import multiple names | from math import sqrt, pi | When a few names are needed |
| Import all names | from 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 ───────────┘- Create Module: Write functions, classes, variables.
- Write & Test: Test with different inputs.
- Package Module: Organize with
__init__.pyand metadata. - Distribute: Share through PyPI or private repository.
- Import & Reuse: Import into programs; install via
pip.
Iterate & Improve: Fix bugs, optimize, add features, and redistribute.
Q18. 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.
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 Type | Python Equivalent | Example |
|---|---|---|
| object | dict | {"name": "Amit"} |
| array | list | [10, 20, 30] |
| string | str | "Python" |
| number | int or float | 25 or 3.14 |
| true / false | True / False | true becomes True |
| null | None | null becomes None |
3. The json Module
Python provides the built-in json module for working with JSON data.
| Function | Purpose |
|---|---|
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"]) # 885. 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]) # Python6. 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 Error | Reason | Solution |
|---|---|---|
JSONDecodeError | Invalid JSON syntax (missing quotes, extra comma) | Validate JSON format before parsing |
KeyError | Trying to access a key that does not exist | Use get() or check if key exists |
TypeError | Trying to serialize an unsupported Python object | Convert 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/Output3. RegEx Metacharacters
| Symbol | Meaning | Example |
|---|---|---|
. | Any single character except newline | a.c matches abc, axc |
^ | Start of string | ^Hello |
$ | End of string | end$ |
* | Zero or more repetitions | ab* matches a, ab, abb |
+ | One or more repetitions | ab+ matches ab, abb |
? | Zero or one repetition | colou?r matches color, colour |
[] | One character from a set | [aeiou] |
\d | Digit | \d+ matches 123 |
\w | Word character | \w+ |
\s | Whitespace | \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 spacesExample 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 Errors3. Key Concepts
Exception Handling:
| Block | Purpose |
|---|---|
try | Code that may raise an exception |
except | Handles specific exceptions |
else | Runs if no exception occurs |
finally | Always runs (cleanup) |
File Modes:
| Mode | Meaning |
|---|---|
r | Read (file must exist) |
w | Write (creates/overwrites) |
a | Append (adds at end) |
x | Create (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,78Sample Output (results.txt):
Total students: 3
Average marks: 85.00
Detailed Results:
Ravi: 85.0
Meena: 92.0
Priya: 78.0Console Output:
Invalid marks for Arjun: invalid
Results saved to results.txt
Processing finished.5. Explanation of Concepts Used
| Concept | Where It Appears |
|---|---|
try-except | Wraps file operations and data processing |
FileNotFoundError | Handles missing input file |
PermissionError | Handles permission issues |
ValueError | Handles invalid marks conversion |
with open() | Auto-closes files safely |
encoding="utf-8" | Supports multilingual text |
finally | Ensures cleanup message runs |
| Nested try-except | Handles per-line errors without crashing |
6. Best Practices
- Always use
withfor file operations — auto-closes files. - Catch specific exceptions — avoid bare
except:. - Use
encoding="utf-8"for text files. - Validate data before processing.
- Use
finallyfor cleanup tasks. - Log errors instead of silent failures.
- 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:
- Reads student data from a JSON file.
- Validates email addresses using RegEx.
- Handles file and JSON errors.
- 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.jsonOutput 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
| Step | Action | Code |
|---|---|---|
| 1 | Import modules | import json, import re |
| 2 | Define email pattern | EMAIL_PATTERN = r"^[\w.-]+@[\w.-]+\.\w+$" |
| 3 | Validate email | re.fullmatch(EMAIL_PATTERN, email) |
| 4 | Check required fields | for field in required_fields |
| 5 | Read JSON file | json.load(file) |
| 6 | Filter valid records | List comprehension / loop |
| 7 | Write output file | json.dump(valid_students, file, indent=4) |
| 8 | Handle errors | Multiple except blocks |
7. Error Handling Coverage
| Error | Handling |
|---|---|
| Missing file | except FileNotFoundError |
| Invalid JSON | except json.JSONDecodeError |
| Permission issue | except PermissionError |
| Missing fields | validate_student() checks |
| Invalid email | is_valid_email() checks |
| Unexpected errors | except 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
| Concept | Purpose | Key Functions/Syntax | Common Use Cases | Output |
|---|---|---|---|---|
| Modules | Organize and reuse code | import, from ... import, as, dir() | Code reuse, built-in libraries, package organization | Reusable .py files |
| JSON Processing | Exchange structured data | json.loads(), json.dumps(), json.load(), json.dump() | APIs, config files, data storage | Python objects ↔︎ JSON text/files |
| RegEx | Pattern matching in text | re.search(), re.findall(), re.sub(), re.fullmatch() | Validation, extraction, cleaning | Matched patterns or modified text |
| Exception Handling | Handle runtime errors | try, except, else, finally, raise | Error recovery, resource cleanup | Graceful error messages |
| File Handling | Read/write persistent data | open(), read(), write(), with, modes (r, w, a) | Data storage, logs, configuration | File objects, persistent data |
2. How These Concepts Work Together
| Concept | Role in Application | Interacts With |
|---|---|---|
| Modules | Provide functionality (json, re, os) | All other concepts |
| File Handling | Read input and write output | JSON, RegEx, Exceptions |
| JSON | Parse/store structured data | File handling, Exceptions |
| RegEx | Validate/clean text data | JSON, File handling |
| Exception Handling | Protect all operations | All 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
| Benefit | Description |
|---|---|
| Robustness | Exception handling prevents crashes |
| Data Integrity | RegEx validates input |
| Interoperability | JSON enables data exchange |
| Persistence | File handling stores data permanently |
| Reusability | Modules organize code |
| Maintainability | Clean separation of concerns |
| Scalability | Easy 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:
- Use
withfor file operations. - Catch specific exceptions.
- Validate data with RegEx.
- Use JSON for structured data.
- Organize code into modules.
- Test edge cases (empty files, invalid data, missing keys).