Adv-Python Unit 3: Question with Answers
Unit III: Python Modules and File Handling -> Generated and Prepared By Thiruselvan (ThiruXD)
SECTION A: MULTIPLE CHOICE QUESTIONS (50 MCQs)
Introduction to Python Modules
Q1. Which file extension is used for a Python module?
- .txt
- .py
- .json
- .exe
Answer: B) .py
Explanation: A Python module is a file with a .py extension containing reusable code.
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.
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: import math as m creates an alias m for the math module within the current program only.
Q4. A Python file named calculator.py becomes a module named:
- calculator.py
- calculator
- calc
- module_calculator
Answer: B) calculator
Explanation: The file name becomes the module name without the .py extension.
Q5. A folder that groups related modules is called a:
- Module
- Package
- Library
- Script
Answer: B) Package
Explanation: A package is a folder containing related modules, usually with an __init__.py file.
Q6. Which of the following is a collection of modules and packages designed for specific tasks?
- Module
- Package
- Library
- Function
Answer: C) Library
Explanation: A library is a collection of modules and packages (e.g., NumPy, Pandas).
Q7. Which is NOT a reason for using modules in Python?
- Code reuse
- Organisation
- Slower execution
- Maintainability
Answer: C) Slower execution
Explanation: Modules improve organisation and reuse; they do not intentionally slow execution.
Q8. Which of the following is a valid module name?
- StudentRecords.py
- file-utils.py
- data_cleaning.py
- 3module.py
Answer: C) data_cleaning.py
Explanation: Module names should use lowercase letters and underscores; avoid uppercase, hyphens, and starting with numbers.
Q9. Which of the following module names should be avoided?
- my_math_tools.py
- math.py
- student_records.py
- file_utils.py
Answer: B) math.py
Explanation: Naming a file math.py can hide the built-in math module and cause confusing errors.
Q10. What does a module typically contain?
- Only functions
- Only variables
- Functions, classes, variables, and executable statements
- Only classes
Answer: C) Functions, classes, variables, and executable statements
Explanation: A module is a Python file that can contain all of these elements.
Creating and Using Modules
Q11. Which notation is used to access module members?
- Arrow notation (
>) - Dot notation (
module_name.function_name()) - Bracket notation (
module_name[function]) - Colon notation (
module_name:function)
Answer: B) Dot notation (module_name.function_name())
Explanation: Module members are accessed using dot notation.
Q12. What is the first step in creating a user-defined module?
- Import the module
- Create a Python file with a meaningful name
- Use
dir()function - Write exception handling
Answer: B) Create a Python file with a meaningful name
Explanation: Start by creating a .py file containing the reusable code.
Q13. For beginner-level programs, where should the module file and the main program be located?
- In different drives
- In the same folder
- In the system root
- In the Python installation folder
Answer: B) In the same folder
Explanation: Both files should usually be in the same folder so Python can find the module.
Q14. What does import calculator_tools do?
- Deletes the module
- Loads the module into the program
- Converts the module to JSON
- Compiles the module
Answer: B) Loads the module into the program
Explanation: The import statement loads the module so its members can be used.
Q15. Which of the following is a best practice when creating modules?
- Write all code at module level
- Use meaningless variable names
- Keep each module focused on one main purpose
- Avoid docstrings
Answer: C) Keep each module focused on one main purpose
Explanation: Focused modules are easier to read, test, and maintain.
Importing from Modules
Q16. Which import style is used when many functions from a module are required?
from math import sqrtimport mathfrom math import *import math as m
Answer: B) import math
Explanation: Importing the full module is appropriate when many functions are needed.
Q17. Which import statement imports only the sqrt function?
import sqrtfrom math import sqrtimport math.sqrtfrom math import *
Answer: B) from math import sqrt
Explanation: from module import name imports a specific function or variable.
Q18. Which import style is generally avoided because it can create name conflicts?
import mathimport math as mfrom math import sqrtfrom math import *
Answer: D) from math import *
Explanation: Importing all names can overwrite existing names and cause conflicts.
Q19. What is the purpose of the __name__ variable?
- Stores the module’s file path
- Determines whether a file is run directly or imported
- Stores the module’s version
- Lists module contents
Answer: B) Determines whether a file is run directly or imported
Explanation: __name__ is "__main__" when run directly, and the module name when imported.
Q20. When a Python file is run directly, __name__ is set to:
- The file name
"__main__""module"None
Answer: B) "__main__"
Explanation: Python sets __name__ to "__main__" for the directly executed file.
Q21. What does the if __name__ == "__main__": pattern prevent?
- Syntax errors
- Test code from running automatically when a module is imported
- Module import
- File creation
Answer: B) Test code from running automatically when a module is imported
Explanation: This pattern ensures test code runs only when the file is executed directly.
Built-in Modules and dir()
Q22. Which function lists names available inside a module?
list()names()dir()show()
Answer: C) dir()
Explanation: dir(module) returns a list of names available in the module.
Q23. Which built-in module is used for mathematical functions?
randommathossys
Answer: B) math
Explanation: The math module provides functions like sqrt(), ceil(), and constants like pi.
Q24. Which built-in module is used for random number generation?
mathrandomstatisticsdatetime
Answer: B) random
Explanation: The random module provides randint(), choice(), shuffle(), etc.
Q25. Which built-in module is used for working with dates and times?
timedatetimecalendardate
Answer: B) datetime
Explanation: The datetime module provides date.today() and datetime.now().
Q26. Which built-in module provides basic statistics functions?
mathstatisticsrandomnumpy
Answer: B) statistics
Explanation: The statistics module provides mean(), median(), and mode().
Q27. What does dir(str) display?
- Names in the current scope
- Methods available for string objects
- Contents of the math module
- File directory listing
Answer: B) Methods available for string objects
Explanation: dir(str) returns string methods like upper(), lower(), split(), etc.
Q28. Which built-in module is used for JSON parsing and conversion?
jsonreossys
Answer: A) json
Explanation: The json module provides loads(), dumps(), load(), and dump().
JSON in Python
Q29. What does JSON stand for?
- Java Standard Object Notation
- JavaScript Object Notation
- Java Serialized Object Network
- JavaScript Online Notation
Answer: B) JavaScript Object Notation
Explanation: JSON is a lightweight text format for storing and exchanging structured data.
Q30. Which JSON type maps to a Python dict?
- array
- object
- string
- number
Answer: B) object
Explanation: JSON objects (key-value pairs) map to Python dictionaries.
Q31. Which JSON value maps to Python None?
falsenull0""
Answer: B) null
Explanation: JSON null becomes Python None.
Q32. Which json function converts a JSON string into a Python object?
json.dumps()json.loads()json.dump()json.convert()
Answer: B) json.loads()
Explanation: loads() parses a JSON string into a Python object (the ‘s’ stands for string).
Q33. Which json function writes a Python object into a JSON file?
json.write()json.save()json.dump()json.loads()
Answer: C) json.dump()
Explanation: dump() writes a Python object to a file in JSON format.
Q34. Which json function converts a Python object into a JSON-formatted string?
json.loads()json.dumps()json.load()json.dump()
Answer: B) json.dumps()
Explanation: dumps() converts a Python object into a JSON string.
Q35. Which json function reads JSON data from a file?
json.loads()json.dumps()json.load()json.dump()
Answer: C) json.load()
Explanation: load() reads JSON data from a file into a Python object.
Q36. What error occurs when parsing invalid JSON syntax?
KeyErrorTypeErrorJSONDecodeErrorValueError
Answer: C) JSONDecodeError
Explanation: JSONDecodeError is raised for invalid JSON syntax like missing quotes or extra commas.
Q37. Which method safely reads an optional JSON key?
data["name"]data.get("name", "Unknown")data.fetch("name")data.read("name")
Answer: B) data.get("name", "Unknown")
Explanation: get() returns a default value if the key doesn’t exist, avoiding KeyError.
Regular Expressions
Q38. Which module is used for regular expressions in Python?
regexrestringpattern
Answer: B) re
Explanation: The re module provides RegEx functions like search(), findall(), and sub().
Q39. Which RegEx metacharacter matches any single character except newline?
.^$
Answer: B) .
Explanation: The dot . matches any single character except newline.
Q40. Which RegEx symbol matches the start of a string?
$^+
Answer: B) ^
Explanation: ^ anchors the pattern to the beginning of the string.
Q41. Which RegEx metacharacter matches one or more repetitions?
+?.
Answer: B) +
Explanation: + matches one or more repetitions (e.g., ab+ matches ab, abb).
Q42. 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 matches with new text.
Q43. Which RegEx function checks whether the entire string matches the pattern?
re.search()re.match()re.fullmatch()re.findall()
Answer: C) re.fullmatch()
Explanation: fullmatch() checks that the entire string matches the pattern.
Q44. Which RegEx function returns all matching substrings as a list?
re.search()re.findall()re.match()re.fullmatch()
Answer: B) re.findall()
Explanation: findall() returns all non-overlapping matches as a list.
Q45. Why are raw strings used for RegEx patterns?
- They are faster
- They avoid confusion with Python escape characters
- They are required
- They enable Unicode
Answer: B) They avoid confusion with Python escape characters
Explanation: Raw strings (r"pattern") prevent \n, \t, etc. from being interpreted as escape sequences.
Exception Handling and File Handling
Q46. Which exception occurs when a program tries to divide by zero?
ValueErrorTypeErrorZeroDivisionErrorIndexError
Answer: C) ZeroDivisionError
Explanation: ZeroDivisionError is raised for division by zero.
Q47. Which exception occurs when a file does not exist?
FileNotFoundErrorKeyErrorIndexErrorTypeError
Answer: A) FileNotFoundError
Explanation: FileNotFoundError is raised when trying to open a nonexistent file.
Q48. Which block runs whether or not an exception occurs?
tryexceptelsefinally
Answer: D) finally
Explanation: The finally block always executes, making it ideal for cleanup.
Q49. Which file mode creates or overwrites a file?
rwax
Answer: B) w
Explanation: Write mode (w) creates a new file or overwrites an existing one.
Q50. Which file mode appends content at the end of a file?
rwax
Answer: C) a
Explanation: Append mode (a) adds content at the end of the file without overwriting.
SECTION B: THEORY QUESTIONS (20)
Q1. Define a Python module. Explain any four advantages of using modules in Python programs.
Answer:
A module is a Python file with a .py extension that contains reusable code such as functions, classes, variables, and executable statements. The file name becomes the module name without the extension.
Four Advantages:
| Advantage | Explanation | Example |
|---|---|---|
| Code Reuse | Write once, use in many programs | Same tax calculation function in multiple billing programs |
| Organisation | Separate large programs into logical files | Database code, validation code, report code in separate modules |
| Maintainability | Change one module without rewriting the full application | Update one email-sending module used across the project |
| Testing | Test individual modules independently | Test calculator functions before using in main program |
Additional advantages: Teamwork (different developers on different modules), reduced development time, consistency across projects.
Q2. Explain the difference between module, package, and library.
Answer:
| Concept | Meaning | Simple Example |
|---|---|---|
| Module | One Python file containing reusable code | math_tools.py |
| Package | A folder that groups related modules; usually contains __init__.py | data_utils/ folder with cleaning.py, validation.py |
| Library | A collection of modules and packages designed for specific tasks | NumPy, Pandas, Matplotlib |
Hierarchy: Library ⊃ Package ⊃ Module
A module is the smallest unit. A package organizes multiple modules into a folder. A library is a broader collection of packages and modules.
Q3. Explain the difference between import module, import module as alias, and from module import name with examples.
Answer:
| Import Style | Syntax | When to Use | Example |
|---|---|---|---|
| Import full module | import math | When many functions are required | math.sqrt(25) |
| Import with alias | import math as m | When a shorter name improves readability | m.sqrt(25) |
| Import one name | from math import sqrt | When only one function is needed | sqrt(25) |
| Import multiple names | from math import sqrt, pi | When a few selected names are needed | sqrt(25), pi |
| Import all names | from math import * | Generally avoided due to name conflicts | sqrt(25) |
Examples:
# Import full module
import math
print(math.sqrt(81)) # 9.0
# Import with alias
import math as m
print(m.factorial(5)) # 120
# Import specific names
from math import sqrt, pi
print(sqrt(81)) # 9.0
print(pi) # 3.14159...Best Practice: Use import module or import module as alias for clarity; avoid from module import *.
Q4. 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, and data transfer.
Functions:
| Function | Purpose | Works With |
|---|---|---|
json.loads() | Parses a JSON string into a Python object | Strings |
json.dumps() | Converts a Python object into a JSON-formatted string | Strings |
json.load() | Reads JSON data from a file into a Python object | Files |
json.dump() | Writes a Python object into a file in JSON format | Files |
Memory Aid: loads/dumps → strings (the ‘s’ stands for string); load/dump → files.
Examples:
import json
# json.loads() — parse JSON string
student_json = '{"name": "Ravi", "age": 21}'
student = json.loads(student_json)
print(student["name"]) # Ravi
# json.dumps() — convert to JSON string
student = {"name": "Ravi", "age": 21}
json_string = json.dumps(student, indent=4)
# json.dump() — write to file
with open("student.json", "w") as file:
json.dump(student, file, indent=4)
# json.load() — read from file
with open("student.json", "r") as file:
data = json.load(file)
print(data["name"])Q5. Explain any five RegEx metacharacters and their use in text processing.
Answer:
| Symbol | Meaning | Example | Use |
|---|---|---|---|
. | Any single character except newline | a.c matches abc, axc | Flexible matching |
^ | Start of string | ^Hello | Validate prefixes |
$ | End of string | end$ | Validate suffixes |
* | Zero or more repetitions | ab* matches a, ab, abb | Optional repeated patterns |
+ | One or more repetitions | ab+ matches ab, abb | Required repeated patterns |
? | Zero or one repetition | colou?r matches color, colour | Optional characters |
[] | One character from a set | [aeiou] | Character classes |
\d | Digit | \d+ matches 123 | Extract numbers |
\w | Word character | \w+ | Extract words |
\s | Whitespace | \s+ | Match spaces/tabs |
Example:
import re
text = "My marks are 85 and attendance is 92"
numbers = re.findall(r"\d+", text)
print(numbers) # ['85', '92']Q6. Write short notes on try, except, else, finally, and multiple exception handling in Python.
Answer:
| Block | Purpose | When It Runs |
|---|---|---|
try | Contains code that may raise an exception | Always attempted |
except | Handles a specific exception | When matching exception occurs |
else | Runs if no exception occurred | Only if try succeeds |
finally | Cleanup code | Always, regardless of exceptions |
Multiple Exception Handling: Multiple except blocks handle different errors. Python checks them top to bottom and runs the first match.
Example:
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:
print("Division successful.")
finally:
print("Program finished.")Best Practice: Avoid bare except: blocks; catch specific exceptions.
Q7. Explain different file opening modes in Python with examples.
Answer:
| Mode | Meaning | Use Case | Example |
|---|---|---|---|
r | Read mode. File must exist | Read existing text file | open("data.txt", "r") |
w | Write mode. Creates or overwrites | Save new output | open("out.txt", "w") |
a | Append mode. Adds at end | Add log messages | open("log.txt", "a") |
x | Create mode. Fails if exists | Create new file safely | open("new.txt", "x") |
b | Binary mode | Read images, audio | open("img.png", "rb") |
t | Text mode (default) | Read normal text | open("data.txt", "rt") |
+ | Read and write mode | Update file content | open("data.txt", "r+") |
Examples:
# Read
with open("students.txt", "r") as file:
print(file.read())
# Write
with open("output.txt", "w") as file:
file.write("First line\n")
# Append
with open("output.txt", "a") as file:
file.write("Appended line\n")Best Practice: Use the with statement to auto-close files.
Q8. What is the purpose of the dir() function? Give examples.
Answer:
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.
Use of dir() | Meaning |
|---|---|
dir(math) | Names available in the math module |
dir(str) | Methods available for string objects |
dir() | Names available in the current scope |
Example:
import math
print(dir(math))
# ['__doc__', '__loader__', ..., 'ceil', 'cos', 'pi', 'sqrt', ...]
print(dir(str))
# ['__add__', 'capitalize', 'upper', 'lower', 'split', ...]Use Case: Discovering available functions before using a module.
Q9. Explain the __name__ == "__main__" pattern with an example.
Answer:
When a Python file is run directly, __name__ is set to "__main__". When the same file is imported as a module, __name__ becomes the module name. This allows a file to contain test code that runs only when executed directly.
Example:
# File: greetings.py
def welcome(name):
return "Welcome, " + name
if __name__ == "__main__":
print(welcome("Student"))- Running
python greetings.py→ prints “Welcome, Student” - Importing
greetingsin another file → test code does NOT run
Why It Matters: Prevents test code from running automatically when the module is imported, avoiding unwanted side effects.
Q10. What is an exception? Explain common exceptions in Python.
Answer: An exception is an error that occurs during program execution. Without handling, the program stops immediately. With handling, the program can display a message, recover, or close resources safely.
Common 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 missing | student["age"] |
IndexError | List index out of range | items[10] |
TypeError | Incompatible types | "5" + 2 |
Handling:
try:
number = int(input("Enter a number: "))
print(100 / number)
except ValueError:
print("Please enter only numbers.")
except ZeroDivisionError:
print("Cannot divide by zero.")Q11. Explain the difference between json.loads() and json.load().
Answer:
| Aspect | json.loads() | json.load() |
|---|---|---|
| Input | JSON string | JSON file object |
| Output | Python object | Python object |
| Use case | Parse API responses, string data | Read JSON from file |
| Memory aid | ‘s’ = string | No ‘s’ = file |
Example:
import json
# json.loads() — from string
json_string = '{"name": "Ravi", "age": 21}'
data = json.loads(json_string)
# json.load() — from file
with open("student.json", "r") as file:
data = json.load(file)Similarly, json.dumps() converts a Python object to a string, while json.dump() writes it to a file.
Q12. Explain the difference between re.search(), re.match(), and re.fullmatch().
Answer:
| Function | Where It Searches | Returns |
|---|---|---|
re.search() | Anywhere in the string | First match |
re.match() | Only at the beginning | Match or None |
re.fullmatch() | Entire string must match | Match or None |
Example:
import re
text = "Hello World"
print(re.search(r"World", text)) # Match found
print(re.match(r"World", text)) # None (not at start)
print(re.match(r"Hello", text)) # Match found
print(re.fullmatch(r"Hello", text)) # None (entire string doesn't match)
print(re.fullmatch(r"Hello World", text)) # Match foundUse Cases:
search(): Find a pattern anywhere.match(): Validate prefix.fullmatch(): Validate entire input (e.g., email, phone).
Q13. What is a user-defined module? Explain the steps to create one.
Answer: A user-defined module is a Python file created by the programmer containing reusable code (functions, classes, variables).
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: calculator_tools.py
def add(a, b):
return a + b
PI = 3.14159
# File: main.py
import calculator_tools
print(calculator_tools.add(10, 5)) # 15
print(calculator_tools.PI) # 3.14159Best Practices: Keep modules focused, use meaningful names, add docstrings, test independently.
Q14. Explain file handling with the with statement. Why is it preferred?
Answer:
The with statement is a context manager that automatically closes the file after the block executes, even if an exception occurs.
Syntax:
with open("file.txt", "r") as file:
content = file.read()
# File is automatically closed hereWhy Preferred:
- Automatic cleanup: File is closed even if an error occurs.
- Cleaner code: No need for explicit
file.close(). - Resource safety: Prevents resource leaks.
- Exception-safe: Works correctly with exceptions.
Comparison:
# Manual (error-prone)
file = open("data.txt", "r")
content = file.read()
file.close() # Must remember to close
# With statement (recommended)
with open("data.txt", "r") as file:
content = file.read()Q15. Explain JSON data type mapping to Python with examples.
Answer:
| 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 |
Example:
import json
json_string = '''
{
"name": "Ravi",
"age": 21,
"marks": [85, 90, 88],
"is_active": true,
"address": null
}
'''
data = json.loads(json_string)
print(type(data)) # <class 'dict'>
print(data["marks"]) # [85, 90, 88]
print(data["is_active"]) # True
print(data["address"]) # NoneNote: JSON keys are always strings; Python dict values can be any type.
Q16. Explain the workflow of Python module creation and reuse.
Answer: The Python module workflow consists of five steps:
- Create Module: Write code (functions, classes, variables) in a
.pyfile. - Write & Test: Test with different inputs to verify correctness and reliability.
- Package Module: Organize into standard directory structure with
__init__.py, metadata. - Distribute: Share through PyPI or private repository; version release.
- Import & Reuse: Import into multiple programs using
pip installandimport.
Iterate & Improve: The workflow is not one-time. After use, developers fix bugs, optimize, add features, and redistribute as newer versions.
Diagram:
Create → Test → Package → Distribute → Import & Reuse
↑ │
└──────────── Iterate & Improve ───────────┘Q17. Discuss built-in modules in Python with examples.
Answer: Python includes many ready-to-use modules in its standard library.
| Module | Purpose | Example |
|---|---|---|
math | Mathematical functions | sqrt(), ceil(), pi |
random | Random number generation | randint(), choice(), shuffle() |
datetime | Dates and times | date.today(), datetime.now() |
os | Operating system interaction | listdir(), mkdir(), path.exists() |
sys | Python interpreter info | sys.version, sys.path |
json | JSON parsing | loads(), dumps(), load(), dump() |
re | Regular expressions | 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())Advantage: No installation required; always available.
Q18. Explain how to read and write JSON files in Python.
Answer:Writing JSON to a file:
import json
student = {
"name": "Meena",
"semester": 5,
"skills": ["Python", "SQL"]
}
with open("student.json", "w") as file:
json.dump(student, file, indent=4)Reading JSON from a file:
import json
with open("student.json", "r") as file:
data = json.load(file)
print(data["skills"]) # ['Python', 'SQL']Key Points:
json.dump()writes Python object to file in JSON format.json.load()reads JSON from file into Python object.- Use
indent=4for readable formatting. - Use
withstatement for automatic file closing.
Error Handling:
try:
with open("student.json", "r") as file:
data = json.load(file)
except FileNotFoundError:
print("File not found.")
except json.JSONDecodeError:
print("Invalid JSON format.")Q19. Explain the re module functions with examples.
Answer:
| Function | Purpose | Example |
|---|---|---|
re.search() | Searches anywhere; returns first match | re.search(r"\d+", "abc123") |
re.match() | Matches only at beginning | re.match(r"abc", "abc123") |
re.fullmatch() | Entire string must match | re.fullmatch(r"\d+", "123") |
re.findall() | Returns all matches as list | re.findall(r"\d+", "a1b2c3") |
re.finditer() | Returns match objects one by one | re.finditer(r"\d+", "a1b2") |
re.split() | Splits string by pattern | re.split(r"\s+", "a b c") |
re.sub() | Replaces matches | re.sub(r"\d+", "X", "a1b2") |
re.compile() | Compiles pattern for reuse | p = re.compile(r"\d+") |
Example:
import re
# findall
text = "My marks are 85 and 92"
print(re.findall(r"\d+", text)) # ['85', '92']
# fullmatch — validate email
email = "student@example.com"
pattern = r"^[\w.-]+@[\w.-]+\.\w+$"
print(re.fullmatch(pattern, email)) # Match
# sub — clean whitespace
sentence = "Python is easy"
print(re.sub(r"\s+", " ", sentence)) # Python is easy
# split
print(re.split(r",", "a,b,c")) # ['a', 'b', 'c']Raw Strings: Use r"pattern" to avoid escape character confusion.
Q20. Explain how modules, JSON, RegEx, exception handling, and file handling can be combined in a real-world application.
Answer: A real-world application (e.g., student record management) combines all concepts:
Scenario: Read student data from JSON, validate emails using RegEx, handle errors, and save valid records.
import json
import re
EMAIL_PATTERN = r"^[\w.-]+@[\w.-]+\.\w+$"
try:
with open("students.json", "r", encoding="utf-8") as file:
students = json.load(file)
valid_students = []
for student in students:
email = student.get("email", "")
if re.fullmatch(EMAIL_PATTERN, email):
valid_students.append(student)
with open("valid_students.json", "w", encoding="utf-8") as file:
json.dump(valid_students, file, indent=4)
print("Valid records saved.")
except FileNotFoundError:
print("Input file not found.")
except json.JSONDecodeError:
print("Invalid JSON format.")
except Exception as error:
print("Unexpected error:", error)Concepts Demonstrated:
| Concept | Where It Appears |
|---|---|
| Module import | import json, import re |
| JSON parsing | json.load(file) |
| RegEx validation | re.fullmatch() |
| File writing | json.dump() |
| Exception handling | try-except blocks |
Real-World Applications: Log analysis, student record management, API data processing, configuration validation.
SECTION C: ANALYTICAL QUESTIONS (10)
Q1. Analyze the following code and predict the output. Explain each line.
# File: mymodule.py
def greet(name):
return "Hello, " + name
PI = 3.14
if __name__ == "__main__":
print(greet("World"))
# File: main.py
import mymodule
print(mymodule.greet("Alice"))
print(mymodule.PI)Answer:
Output when running mymodule.py directly:
Hello, WorldOutput when running main.py:
Hello, Alice
3.14Line-by-Line Explanation:
| Line | Explanation |
|---|---|
def greet(name): | Defines a function in the module |
PI = 3.14 | Module-level variable |
if __name__ == "__main__": | Checks if file is run directly |
print(greet("World")) | Runs only when mymodule.py is executed directly |
import mymodule | Loads the module into main.py |
mymodule.greet("Alice") | Calls the function using dot notation |
mymodule.PI | Accesses module-level variable |
Key Insight: When main.py imports mymodule, the if __name__ == "__main__" block does NOT run, preventing unwanted output.
Q2. Analyze the following JSON handling code. Identify potential errors and suggest improvements.
import json
data = '{"name": "Ravi", "age": 21,}'
student = json.loads(data)
print(student["marks"])Answer:
Errors Identified:
- Trailing comma in JSON:
{"name": "Ravi", "age": 21,}has a trailing comma after21, which is invalid JSON. This raisesjson.JSONDecodeError. - Missing key access:
student["marks"]will raiseKeyErrorbecause “marks” is not in the JSON.
Corrected Code:
import json
data = '{"name": "Ravi", "age": 21}'
try:
student = json.loads(data)
print(student["name"]) # Ravi
print(student.get("marks", "Not available")) # Not available
except json.JSONDecodeError:
print("Invalid JSON format.")
except KeyError as e:
print("Missing key:", e)Improvements:
- Remove trailing comma.
- Use
get()for optional keys. - Add exception handling.
- Validate JSON before parsing.
Q3. A student writes the following code to validate email addresses. Identify the issues and fix them.
import re
email = "student@example.com"
pattern = "^[w.-]+@[w.-]+.w+$"
if re.match(pattern, email):
print("Valid")
else:
print("Invalid")Answer:
Issues Identified:
- Missing backslashes:
wand.should be\wand\.. Without backslashes, they are literal characters, not metacharacters. - Unescaped dot: The dot before
w+should be\.to match a literal dot, not any character. re.match()vsre.fullmatch():re.match()only checks the beginning. For full validation, usere.fullmatch().- Raw string: Pattern should use raw string
r"..."to avoid escape issues.
Corrected Code:
import re
email = "student@example.com"
pattern = r"^[\w.-]+@[\w.-]+\.\w+$"
if re.fullmatch(pattern, email):
print("Valid")
else:
print("Invalid")Explanation:
[\w.-]+matches word characters, dots, and hyphens.@matches literal @.\.\w+matches a literal dot followed by word characters.fullmatch()ensures the entire string matches.
Q4. Analyze the following file handling code. What happens if the file doesn’t exist? How can it be improved?
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()Answer:
Problem: If data.txt doesn’t exist, open() raises FileNotFoundError, and the program crashes. The file is never closed.
Issues:
- No exception handling.
- File may not be closed if an error occurs.
- No encoding specified.
Improved Code:
try:
with open("data.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The file data.txt was not found.")
except Exception as error:
print("Unexpected error:", error)Improvements:
withstatement auto-closes the file.try-excepthandles missing file gracefully.- UTF-8 encoding for multilingual support.
- Generic exception catch for unexpected errors.
Q5. A program reads a JSON file containing student records and writes valid records to a new file. Analyze the following code and identify missing concepts.
import json
with open("students.json", "r") as file:
students = json.load(file)
valid = []
for s in students:
if "@" in s["email"]:
valid.append(s)
with open("valid.json", "w") as file:
json.dump(valid, file)Answer:
Missing Concepts:
- RegEx validation: Using
"@" in emailis too simple; usere.fullmatch()for proper email validation. - Exception handling: No handling for
FileNotFoundErrororJSONDecodeError. - Safe key access:
s["email"]raisesKeyErrorif missing; uses.get("email", ""). - Encoding: No
encoding="utf-8"for file operations. - Indent for readability:
json.dump()withoutindentproduces compact output. - No module import for
re.
Improved Code:
import json
import re
EMAIL_PATTERN = r"^[\w.-]+@[\w.-]+\.\w+$"
try:
with open("students.json", "r", encoding="utf-8") as file:
students = json.load(file)
valid = []
for s in students:
email = s.get("email", "")
if re.fullmatch(EMAIL_PATTERN, email):
valid.append(s)
with open("valid.json", "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("Unexpected error:", error)Q6. Analyze the following exception handling code. What is the output for different inputs?
try:
x = int(input("Enter number: "))
y = int(input("Enter divisor: "))
result = x / y
print("Result:", result)
except ValueError:
print("Invalid input.")
except ZeroDivisionError:
print("Cannot divide by zero.")
else:
print("Division successful.")
finally:
print("Program finished.")Answer:
Case 1: Input 10 and 2
Result: 5.0
Division successful.
Program finished.(No exception; else and finally run.)
Case 2: Input 10 and 0
Cannot divide by zero.
Program finished.(ZeroDivisionError; else skipped; finally runs.)
Case 3: Input abc and 2
Invalid input.
Program finished.(ValueError; else skipped; finally runs.)
Case 4: Input 10 and abc
Invalid input.
Program finished.(ValueError on second input; else skipped; finally runs.)
Key Observations:
elseruns only if no exception.finallyalways runs.- Exceptions are caught by the first matching
exceptblock.
Q7. Design a Python program that reads a text file, counts the number of lines, words, and characters, and handles file errors.
Answer:
def analyze_file(filename):
try:
with open(filename, "r", encoding="utf-8") as file:
content = file.read()
lines = content.splitlines()
words = content.split()
characters = len(content)
print(f"Lines:{len(lines)}")
print(f"Words:{len(words)}")
print(f"Characters:{characters}")
except FileNotFoundError:
print(f"Error: '{filename}' not found.")
except PermissionError:
print(f"Error: Permission denied for '{filename}'.")
except Exception as error:
print("Unexpected error:", error)
# Usage
analyze_file("sample.txt")Explanation:
with open()auto-closes the file.splitlines()counts lines.split()splits on whitespace to count words.len(content)counts characters.- Multiple
exceptblocks handle specific errors. - Generic
exceptcatches unexpected errors.
Sample Output:
Lines: 10
Words: 85
Characters: 512Q8. Analyze the following module import scenarios and predict the output.
# File: math_utils.py
def square(n):
return n * n
print("Module loaded")
# File: main.py
import math_utils
print(math_utils.square(5))Answer:
Output:
Module loaded
25Explanation:
- When
main.pyimportsmath_utils, the entire module is executed. - The
print("Module loaded")statement at module level runs during import. - Then
math_utils.square(5)returns 25.
Issue: The module-level print runs every time the module is imported, which is often unwanted.
Improved Code:
# File: math_utils.py
def square(n):
return n * n
if __name__ == "__main__":
print("Module loaded") # Runs only when executed directlyOutput after improvement (when imported):
25(No “Module loaded” because the file was imported, not run directly.)
Q9. A student wants to validate phone numbers in the format XXX-XXX-XXXX. Write a RegEx pattern and test it.
Answer:
RegEx Pattern:
r"^\d{3}-\d{3}-\d{4}$"Explanation:
^— Start of string\d{3}— Exactly 3 digits- — Literal hyphen
\d{3}— Exactly 3 digits- — Literal hyphen
\d{4}— Exactly 4 digits$— End of string
Test Code:
import re
pattern = r"^\d{3}-\d{3}-\d{4}$"
test_numbers = [
"123-456-7890", # Valid
"1234567890", # Invalid (no hyphens)
"12-345-6789", # Invalid (wrong format)
"123-456-789", # Invalid (only 3 digits at end)
"abc-def-ghij" # Invalid (not digits)
]
for number in test_numbers:
if re.fullmatch(pattern, number):
print(f"{number}: Valid")
else:
print(f"{number}: Invalid")Output:
123-456-7890: Valid
1234567890: Invalid
12-345-6789: Invalid
123-456-789: Invalid
abc-def-ghij: InvalidExtension: For international format, use r"^\+\d{1,3}-\d{3}-\d{3}-\d{4}$".
Q10. Design a complete program that combines modules, JSON, RegEx, exception handling, and file handling to process student records.
Answer:
Scenario: Read student records from a JSON file, validate emails and phone numbers using RegEx, filter valid records, and save them to a new JSON file.
Program:
import json
import re
# RegEx patterns
EMAIL_PATTERN = r"^[\w.-]+@[\w.-]+\.\w+$"
PHONE_PATTERN = r"^\d{3}-\d{3}-\d{4}$"
def validate_student(student):
"""Validate email and phone for a student record."""
email = student.get("email", "")
phone = student.get("phone", "")
return (re.fullmatch(EMAIL_PATTERN, email) and
re.fullmatch(PHONE_PATTERN, phone))
def process_students(input_file, output_file):
try:
# Read JSON file
with open(input_file, "r", encoding="utf-8") as file:
students = json.load(file)
# Validate and filter
valid_students = [s for s in students if validate_student(s)]
# Write valid records
with open(output_file, "w", encoding="utf-8") as file:
json.dump(valid_students, file, indent=4)
print(f"Processed{len(students)} records.")
print(f"Valid records:{len(valid_students)}")
print(f"Invalid records:{len(students) - len(valid_students)}")
except FileNotFoundError:
print(f"Error: '{input_file}' not found.")
except json.JSONDecodeError:
print("Error: Invalid JSON format.")
except PermissionError:
print("Error: Permission denied.")
except Exception as error:
print("Unexpected error:", error)
# Usage
process_students("students.json", "valid_students.json")Sample Input (students.json):
[
{"name": "Ravi", "email": "ravi@example.com", "phone": "123-456-7890"},
{"name": "Meena", "email": "invalid-email", "phone": "123-456-7890"},
{"name": "Arjun", "email": "arjun@test.com", "phone": "12-345-6789"}
]Sample Output:
Processed 3 records.
Valid records: 1
Invalid records: 2Concepts Demonstrated:
| Concept | Implementation |
|---|---|
| Module import | import json, import re |
| JSON parsing | json.load(file) |
| RegEx validation | re.fullmatch() for email and phone |
| File writing | json.dump() with indent |
| Exception handling | Multiple except blocks |
| Functions | validate_student(), process_students() |
| List comprehension | Filtering valid records |
Real-World Applications: Student management systems, CRM data cleaning, API response validation, log processing.
SUMMARY TABLE
| Section | Count | Topics Covered |
|---|---|---|
| MCQ | 50 | Modules, imports, aliases, dir(), JSON, RegEx, exceptions, file handling |
| Theory | 20 | Module concepts, JSON functions, RegEx, exception handling, file modes, integrated examples |
| Analytical | 10 | Code analysis, error identification, pattern design, integrated programs |