PART 3 β€’ LEVEL 10

πŸ“ Modules, Exceptions & Files

Reuse trusted modules, protect programs from runtime failures and store structured information in text, CSV and JSON files.

⏱ 110–125 minutesπŸ“š 8 conceptsπŸ’» 5 programs🧠 6-question quiz
read_report.pyPython 3
try:
    with open("report.txt", "r") as file:
        text = file.read()
        print(text)
except FileNotFoundError:
    print("Report not found")
KEY IDEAOpen safely β€’ close automatically

By the End of This Level

You will be able to connect programs with reusable libraries and persistent data.

01

Import modules and call names through a clear namespace.

02

Handle expected runtime errors with focused exceptions.

03

Read and write files safely using a context manager.

04

Process common CSV and JSON data formats.

01

Module Fundamentals

A module is a Python file that groups related variables, functions and classes for reuse.

import loads a module and gives your program access to its public names. Keeping the module name, as in math.sqrt(), makes the source of each tool visible.

Namespace

A mapping of names to objects. Module namespaces prevent unrelated files from accidentally using the same name.

1ImportLocate the module
β†’
2LoadExecute it once
β†’
3AccessUse module.name
β†’
4ReuseCall trusted logic
EXAMPLE 1

Use the Math Module

import math

radius = 4
area = math.pi * radius ** 2
print(round(area, 2))
Output
50.27
02

Import Styles and Useful Modules

Choose an import style that keeps names readable and avoids hidden collisions.

StyleExampleBest use
Import moduleimport mathClear source: math.sqrt(81)
Import selected namefrom math import sqrtOne frequently used name
Import with aliasimport statistics as statsShort conventional name
Avoid wildcardfrom math import *Usually unclear and collision-prone
πŸ“

math

Numeric constants and functions.

🎲

random

Pseudo-random choices and numbers.

πŸ“…

datetime

Dates, times and durations.

πŸ“Š

statistics

Mean, median and related measures.

03

Exception Handling

An exception is an object that reports a runtime problem and interrupts normal execution unless it is handled.

1tryRun risky code
β†’
2exceptHandle a match
β†’
3elseRun if successful
β†’
4finallyAlways clean up
EXAMPLE 2

Safe Number Conversion

try:
    age = int(input("Age: "))
except ValueError:
    print("Enter a whole number")
else:
    print("Next year:", age + 1)
finally:
    print("Validation complete")
Possible output
Next year: 19
Validation complete
Catch narrowly

Handle the most specific expected exception. A broad except: can hide programming mistakes that should be fixed.

04

Common Exceptions and Raising Errors

Different exception types communicate different causes and support precise recovery.

ExceptionTypical causeExample
ValueErrorRight type of operation, invalid valueint("ten")
ZeroDivisionErrorDivision by zero8 / 0
FileNotFoundErrorMissing file in read modeopen("missing.txt")
KeyErrorMissing dictionary keyprofile["age"]
TypeErrorUnsupported types or call shape"4" + 2
VALIDATE

Reject Invalid Data

Use raise when a function cannot accept the supplied value.

if marks < 0:
    raise ValueError("marks cannot be negative")
MESSAGE

Explain the Cause

A useful error message states what was invalid and what the caller should supply.

raise ValueError("marks must be 0 to 100")
05

File Paths and Modes

A file keeps data after the program finishes. A path identifies the file; a mode controls the permitted operation.

ModeMeaningIf the file existsIf missing
rRead textOpen from the beginningError
wWrite textReplace existing contentCreate
aAppend textAdd at the endCreate
xCreate exclusivelyErrorCreate
bBinary modifierCombine with another mode, such as rb
Path awareness

A relative path starts from the program’s current working directory. An absolute path begins from the filesystem root.

06

Reading and Writing Text Files

Use with open(...) so Python closes the file automatically, including when an exception occurs.

READ

Choose the needed method

read() returns all remaining text, readline() returns one line and iteration processes one line at a time.

with open("notes.txt", "r") as file:
    for line in file:
        print(line.strip())
WRITE

Write explicit text

write() does not add a newline automatically. Include \n when separate lines are required.

with open("result.txt", "w") as file:
    file.write("Passed\n")
Encoding

For predictable text handling across systems, production programs commonly pass encoding="utf-8".

07

Working with CSV

CSV stores records as rows and fields. Python’s csv module handles quoting and delimiters safely.

EXAMPLE 3

Read Student Marks

import csv

with open("marks.csv", "r", newline="") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row[0], row[1])
marks.csv
Asha,88
Ravi,92
Rows are strings

csv.reader() returns each row as a list of strings. Convert numeric fields before calculating with them.

08

Working with JSON

JSON represents objects, arrays, strings, numbers, booleans and null in a portable text format.

LOAD

JSON β†’ Python

json.load(file) reads from an open file. json.loads(text) reads from a string.

with open("profile.json", "r") as file:
    profile = json.load(file)
DUMP

Python β†’ JSON

json.dump(value, file) writes to a file. json.dumps(value) returns a string.

with open("profile.json", "w") as file:
    json.dump(profile, file, indent=2)

JSON objects become dictionaries, arrays become lists, true/false become True/False, and null becomes None.

Applied Python Errors to Avoid

01
Using wildcard imports

They hide where names came from and can overwrite existing names.

02
Catching every exception

Handle only failures the program understands and can recover from.

03
Forgetting the file mode

w replaces existing content, while a preserves it and appends.

04
Parsing structured data manually

Use csv and json so quoting, escaping and types are handled correctly.

QUICK REVISION

πŸ“Œ Modules, Exceptions & Files β€” Quick Revision

Review these ten rules before attempting the quiz and programming problems.

01

A module groups reusable Python code.

02

module.name keeps a tool’s source clear.

03

try contains code that may raise an expected exception.

04

except should name the most specific useful type.

05

else runs only when try succeeds.

06

finally runs whether an exception occurs or not.

07

with open(...) closes a file automatically.

08

Mode w replaces; mode a appends.

09

csv.reader() produces rows of strings.

10

json.load() converts JSON into Python values.

🧠 Level 10 Quiz

Select one answer for each question, then check your score.

1. Which statement keeps the module namespace visible?

2. Which block runs only when the try block finishes without an exception?

3. Which exception does int("twelve") raise?

4. Which mode adds new text without deleting existing content?

5. Why is with open(...) preferred?

6. Which function reads JSON from an already-open file?

PROGRAMMING PROBLEMS

πŸ’» CodeBhavya Applied Python Challenges

Write and run each program in the browser. File problems use the displayed virtual files so nothing on your device is changed.

0 / 5Solved independently
0Completed with solution
0 / 500Best score
0%Progress
1. Circle Area with math

Import math, read a radius and display the circle area rounded to two decimal places.

Sample input: 4Expected output: Area = 50.27
2. Safe Integer Division

Read two integers. Display the quotient, or a clear message when the divisor is zero.

Sample inputs: 18, 0Expected output: Cannot divide by zero
3. Text File Report

Read notes.txt and display its number of lines and words.

Virtual file: Learn Python\nPractice daily\nBuild projectsExpected output: Lines = 3 and Words = 6
4. CSV Marks Average

Read the three rows in marks.csv and display the whole-number average.

Virtual file: Asha,84 β€’ Ravi,90 β€’ Mina,96Expected output: Average = 90
5. JSON Profile Summary

Load profile.json and display the learner’s name and number of skills.

Virtual file: {"name":"Bhavya","skills":["Python","C","DSA"]}Expected output: Name = Bhavya and Skills = 3
KEY TAKEAWAY

🎯 Build Programs That Connect and Recover

1Import Clearly

Reuse tools through namespaces.

β†’
2Validate Risk

Expect realistic failures.

β†’
3Manage Files

Open safely with with.

β†’
4Parse Formats

Use CSV and JSON libraries.

Applied Python programs depend on more than calculations. They reuse existing code, communicate failures deliberately and transform persistent data without leaving resources open or formats half-parsed.

INTERACTIVE LEARNING

🎬 Safe File Processing β€” Visual Flow

Follow one file-processing task from opening the resource to a safe, parsed result.

PROGRAM TRACING

πŸ”Ž Program Tracing β€” Safe Division

Trace how try transfers control to the matching except block when the divisor is zero.

INTERVIEW PREPARATION

🎀 Modules, Exceptions & Files β€” Interview Questions

Answer aloud before opening each explanation.

1.

What is the difference between a module and a package?

2.

Why is import math often clearer than a wildcard import?

3.

How do else and finally differ in exception handling?

4.

Why should exceptions be caught specifically?

5.

What problem does a context manager solve for files?

6.

What is the difference between json.load() and json.loads()?

EXTRA TIPS

πŸ’‘ Modules, Exceptions & Files β€” Extra Tips

  • 01

    Prefer explicit imports so readers can locate each external name quickly.

  • 02

    Keep try blocks small; include only statements expected to fail together.

  • 03

    Log or display an actionable error message instead of silently ignoring failure.

  • 04

    Use with for every file unless a longer resource lifetime is intentionally required.

  • 05

    Convert CSV fields to numeric types before totals, comparisons or averages.

  • 06

    Validate JSON keys and types when data comes from outside your program.

EXTRA PRACTICE

✍️ Modules, Exceptions & Files β€” Extra Practice Questions

  1. Use math.sqrt() to display the square root of a valid positive number.
  2. Import statistics with an alias and calculate a list’s mean.
  3. Catch invalid integer input and ask the user to try again.
  4. Raise ValueError when marks fall outside 0 to 100.
  5. Count uppercase letters stored in a text file.
  6. Append a dated study note without replacing earlier notes.
  7. Copy only non-empty lines from one text file to another.
  8. Read a CSV expense file and display its largest amount.
  9. Write a dictionary to JSON using an indentation of two spaces.
  10. Handle both missing-file and invalid-JSON errors with separate messages.

Modules, Exceptions & Files Complete

When you can import clearly, recover from expected failures and process text, CSV and JSON data safely, mark this level complete and continue.