BTCE | 5th Sem
Adv-Python SubjectUnit 3

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?

  1. .txt
  2. .py
  3. .json
  4. .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?

  1. include
  2. import
  3. module
  4. 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?

  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: 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:

  1. calculator.py
  2. calculator
  3. calc
  4. 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:

  1. Module
  2. Package
  3. Library
  4. 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?

  1. Module
  2. Package
  3. Library
  4. 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?

  1. Code reuse
  2. Organisation
  3. Slower execution
  4. 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?

  1. StudentRecords.py
  2. file-utils.py
  3. data_cleaning.py
  4. 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?

  1. my_math_tools.py
  2. math.py
  3. student_records.py
  4. 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?

  1. Only functions
  2. Only variables
  3. Functions, classes, variables, and executable statements
  4. 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?

  1. Arrow notation (>)
  2. Dot notation (module_name.function_name())
  3. Bracket notation (module_name[function])
  4. 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?

  1. Import the module
  2. Create a Python file with a meaningful name
  3. Use dir() function
  4. 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?

  1. In different drives
  2. In the same folder
  3. In the system root
  4. 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?

  1. Deletes the module
  2. Loads the module into the program
  3. Converts the module to JSON
  4. 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?

  1. Write all code at module level
  2. Use meaningless variable names
  3. Keep each module focused on one main purpose
  4. 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?

  1. from math import sqrt
  2. import math
  3. from math import *
  4. 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?

  1. import sqrt
  2. from math import sqrt
  3. import math.sqrt
  4. from 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?

  1. import math
  2. import math as m
  3. from math import sqrt
  4. from 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?

  1. Stores the module’s file path
  2. Determines whether a file is run directly or imported
  3. Stores the module’s version
  4. 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:

  1. The file name
  2. "__main__"
  3. "module"
  4. None

Answer: B) "__main__"

Explanation: Python sets __name__ to "__main__" for the directly executed file.


Q21. What does the if __name__ == "__main__": pattern prevent?

  1. Syntax errors
  2. Test code from running automatically when a module is imported
  3. Module import
  4. 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?

  1. list()
  2. names()
  3. dir()
  4. 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?

  1. random
  2. math
  3. os
  4. sys

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?

  1. math
  2. random
  3. statistics
  4. datetime

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?

  1. time
  2. datetime
  3. calendar
  4. date

Answer: B) datetime

Explanation: The datetime module provides date.today() and datetime.now().


Q26. Which built-in module provides basic statistics functions?

  1. math
  2. statistics
  3. random
  4. numpy

Answer: B) statistics

Explanation: The statistics module provides mean(), median(), and mode().


Q27. What does dir(str) display?

  1. Names in the current scope
  2. Methods available for string objects
  3. Contents of the math module
  4. 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?

  1. json
  2. re
  3. os
  4. sys

Answer: A) json

Explanation: The json module provides loads(), dumps(), load(), and dump().


JSON in Python

Q29. What does JSON stand for?

  1. Java Standard Object Notation
  2. JavaScript Object Notation
  3. Java Serialized Object Network
  4. 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?

  1. array
  2. object
  3. string
  4. number

Answer: B) object

Explanation: JSON objects (key-value pairs) map to Python dictionaries.


Q31. Which JSON value maps to Python None?

  1. false
  2. null
  3. 0
  4. ""

Answer: B) null

Explanation: JSON null becomes Python None.


Q32. 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: 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?

  1. json.write()
  2. json.save()
  3. json.dump()
  4. 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?

  1. json.loads()
  2. json.dumps()
  3. json.load()
  4. 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?

  1. json.loads()
  2. json.dumps()
  3. json.load()
  4. 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?

  1. KeyError
  2. TypeError
  3. JSONDecodeError
  4. ValueError

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?

  1. data["name"]
  2. data.get("name", "Unknown")
  3. data.fetch("name")
  4. 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?

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

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?

  1. .
  2. ^
  3. $

Answer: B) .

Explanation: The dot . matches any single character except newline.


Q40. Which RegEx symbol matches the start of a string?

  1. $
  2. ^
  3. +

Answer: B) ^

Explanation: ^ anchors the pattern to the beginning of the string.


Q41. Which RegEx metacharacter matches one or more repetitions?

  1. +
  2. ?
  3. .

Answer: B) +

Explanation: + matches one or more repetitions (e.g., ab+ matches ab, abb).


Q42. 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 matches with new text.


Q43. Which RegEx function checks whether the entire string matches the pattern?

  1. re.search()
  2. re.match()
  3. re.fullmatch()
  4. 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?

  1. re.search()
  2. re.findall()
  3. re.match()
  4. 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?

  1. They are faster
  2. They avoid confusion with Python escape characters
  3. They are required
  4. 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?

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

Answer: C) ZeroDivisionError

Explanation: ZeroDivisionError is raised for division by zero.


Q47. Which exception occurs when a file does not exist?

  1. FileNotFoundError
  2. KeyError
  3. IndexError
  4. TypeError

Answer: A) FileNotFoundError

Explanation: FileNotFoundError is raised when trying to open a nonexistent file.


Q48. Which block runs whether or not an exception occurs?

  1. try
  2. except
  3. else
  4. finally

Answer: D) finally

Explanation: The finally block always executes, making it ideal for cleanup.


Q49. Which file mode creates or overwrites a file?

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

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?

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

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:

AdvantageExplanationExample
Code ReuseWrite once, use in many programsSame tax calculation function in multiple billing programs
OrganisationSeparate large programs into logical filesDatabase code, validation code, report code in separate modules
MaintainabilityChange one module without rewriting the full applicationUpdate one email-sending module used across the project
TestingTest individual modules independentlyTest 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:

ConceptMeaningSimple Example
ModuleOne Python file containing reusable codemath_tools.py
PackageA folder that groups related modules; usually contains __init__.pydata_utils/ folder with cleaning.py, validation.py
LibraryA collection of modules and packages designed for specific tasksNumPy, 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 StyleSyntaxWhen to UseExample
Import full moduleimport mathWhen many functions are requiredmath.sqrt(25)
Import with aliasimport math as mWhen a shorter name improves readabilitym.sqrt(25)
Import one namefrom math import sqrtWhen only one function is neededsqrt(25)
Import multiple namesfrom math import sqrt, piWhen a few selected names are neededsqrt(25), pi
Import all namesfrom math import *Generally avoided due to name conflictssqrt(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:

FunctionPurposeWorks With
json.loads()Parses a JSON string into a Python objectStrings
json.dumps()Converts a Python object into a JSON-formatted stringStrings
json.load()Reads JSON data from a file into a Python objectFiles
json.dump()Writes a Python object into a file in JSON formatFiles

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:

SymbolMeaningExampleUse
.Any single character except newlinea.c matches abc, axcFlexible matching
^Start of string^HelloValidate prefixes
$End of stringend$Validate suffixes
*Zero or more repetitionsab* matches a, ab, abbOptional repeated patterns
+One or more repetitionsab+ matches ab, abbRequired repeated patterns
?Zero or one repetitioncolou?r matches color, colourOptional characters
[]One character from a set[aeiou]Character classes
\dDigit\d+ matches 123Extract numbers
\wWord character\w+Extract words
\sWhitespace\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:

BlockPurposeWhen It Runs
tryContains code that may raise an exceptionAlways attempted
exceptHandles a specific exceptionWhen matching exception occurs
elseRuns if no exception occurredOnly if try succeeds
finallyCleanup codeAlways, 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:

ModeMeaningUse CaseExample
rRead mode. File must existRead existing text fileopen("data.txt", "r")
wWrite mode. Creates or overwritesSave new outputopen("out.txt", "w")
aAppend mode. Adds at endAdd log messagesopen("log.txt", "a")
xCreate mode. Fails if existsCreate new file safelyopen("new.txt", "x")
bBinary modeRead images, audioopen("img.png", "rb")
tText mode (default)Read normal textopen("data.txt", "rt")
+Read and write modeUpdate file contentopen("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 greetings in 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:

ExceptionWhen It OccursExample
ValueErrorCorrect type but invalid valueint("abc")
ZeroDivisionErrorDivision by zero10 / 0
FileNotFoundErrorFile does not existopen("missing.txt")
KeyErrorDictionary key missingstudent["age"]
IndexErrorList index out of rangeitems[10]
TypeErrorIncompatible 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:

Aspectjson.loads()json.load()
InputJSON stringJSON file object
OutputPython objectPython object
Use caseParse API responses, string dataRead JSON from file
Memory aid‘s’ = stringNo ‘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:

FunctionWhere It SearchesReturns
re.search()Anywhere in the stringFirst match
re.match()Only at the beginningMatch or None
re.fullmatch()Entire string must matchMatch 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 found

Use 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:

  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: 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.14159

Best 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 here

Why Preferred:

  1. Automatic cleanup: File is closed even if an error occurs.
  2. Cleaner code: No need for explicit file.close().
  3. Resource safety: Prevents resource leaks.
  4. 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 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

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"])      # None

Note: 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:

  1. Create Module: Write code (functions, classes, variables) in a .py file.
  2. Write & Test: Test with different inputs to verify correctness and reliability.
  3. Package Module: Organize into standard directory structure with __init__.py, metadata.
  4. Distribute: Share through PyPI or private repository; version release.
  5. Import & Reuse: Import into multiple programs using pip install and import.

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.

ModulePurposeExample
mathMathematical functionssqrt(), ceil(), pi
randomRandom number generationrandint(), choice(), shuffle()
datetimeDates and timesdate.today(), datetime.now()
osOperating system interactionlistdir(), mkdir(), path.exists()
sysPython interpreter infosys.version, sys.path
jsonJSON parsingloads(), dumps(), load(), dump()
reRegular expressionssearch(), 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())

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=4 for readable formatting.
  • Use with statement 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:

FunctionPurposeExample
re.search()Searches anywhere; returns first matchre.search(r"\d+", "abc123")
re.match()Matches only at beginningre.match(r"abc", "abc123")
re.fullmatch()Entire string must matchre.fullmatch(r"\d+", "123")
re.findall()Returns all matches as listre.findall(r"\d+", "a1b2c3")
re.finditer()Returns match objects one by onere.finditer(r"\d+", "a1b2")
re.split()Splits string by patternre.split(r"\s+", "a b c")
re.sub()Replaces matchesre.sub(r"\d+", "X", "a1b2")
re.compile()Compiles pattern for reusep = 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:

ConceptWhere It Appears
Module importimport json, import re
JSON parsingjson.load(file)
RegEx validationre.fullmatch()
File writingjson.dump()
Exception handlingtry-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, World

Output when running main.py:

Hello, Alice
3.14

Line-by-Line Explanation:

LineExplanation
def greet(name):Defines a function in the module
PI = 3.14Module-level variable
if __name__ == "__main__":Checks if file is run directly
print(greet("World"))Runs only when mymodule.py is executed directly
import mymoduleLoads the module into main.py
mymodule.greet("Alice")Calls the function using dot notation
mymodule.PIAccesses 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:

  1. Trailing comma in JSON: {"name": "Ravi", "age": 21,} has a trailing comma after 21, which is invalid JSON. This raises json.JSONDecodeError.
  2. Missing key access: student["marks"] will raise KeyError because “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:

  1. Missing backslashes: w and . should be \w and \.. Without backslashes, they are literal characters, not metacharacters.
  2. Unescaped dot: The dot before w+ should be \. to match a literal dot, not any character.
  3. re.match() vs re.fullmatch(): re.match() only checks the beginning. For full validation, use re.fullmatch().
  4. 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:

  1. No exception handling.
  2. File may not be closed if an error occurs.
  3. 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:

  • with statement auto-closes the file.
  • try-except handles 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:

  1. RegEx validation: Using "@" in email is too simple; use re.fullmatch() for proper email validation.
  2. Exception handling: No handling for FileNotFoundError or JSONDecodeError.
  3. Safe key access: s["email"] raises KeyError if missing; use s.get("email", "").
  4. Encoding: No encoding="utf-8" for file operations.
  5. Indent for readability: json.dump() without indent produces compact output.
  6. 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:

  • else runs only if no exception.
  • finally always runs.
  • Exceptions are caught by the first matching except block.

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 except blocks handle specific errors.
  • Generic except catches unexpected errors.

Sample Output:

Lines: 10
Words: 85
Characters: 512

Q8. 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
25

Explanation:

  • When main.py imports math_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 directly

Output 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: Invalid

Extension: 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: 2

Concepts Demonstrated:

ConceptImplementation
Module importimport json, import re
JSON parsingjson.load(file)
RegEx validationre.fullmatch() for email and phone
File writingjson.dump() with indent
Exception handlingMultiple except blocks
Functionsvalidate_student(), process_students()
List comprehensionFiltering valid records

Real-World Applications: Student management systems, CRM data cleaning, API response validation, log processing.


SUMMARY TABLE

SectionCountTopics Covered
MCQ50Modules, imports, aliases, dir(), JSON, RegEx, exceptions, file handling
Theory20Module concepts, JSON functions, RegEx, exception handling, file modes, integrated examples
Analytical10Code analysis, error identification, pattern design, integrated programs

On this page