Import modules and call names through a clear namespace.
π Modules, Exceptions & Files
Reuse trusted modules, protect programs from runtime failures and store structured information in text, CSV and JSON files.
try:
with open("report.txt", "r") as file:
text = file.read()
print(text)
except FileNotFoundError:
print("Report not found")By the End of This Level
You will be able to connect programs with reusable libraries and persistent data.
Handle expected runtime errors with focused exceptions.
Read and write files safely using a context manager.
Process common CSV and JSON data formats.
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.
A mapping of names to objects. Module namespaces prevent unrelated files from accidentally using the same name.
Use the Math Module
import math
radius = 4
area = math.pi * radius ** 2
print(round(area, 2))50.27
Import Styles and Useful Modules
Choose an import style that keeps names readable and avoids hidden collisions.
| Style | Example | Best use |
|---|---|---|
| Import module | import math | Clear source: math.sqrt(81) |
| Import selected name | from math import sqrt | One frequently used name |
| Import with alias | import statistics as stats | Short conventional name |
| Avoid wildcard | from 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.
Exception Handling
An exception is an object that reports a runtime problem and interrupts normal execution unless it is handled.
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")Next year: 19 Validation complete
Handle the most specific expected exception. A broad except: can hide programming mistakes that should be fixed.
Common Exceptions and Raising Errors
Different exception types communicate different causes and support precise recovery.
| Exception | Typical cause | Example |
|---|---|---|
ValueError | Right type of operation, invalid value | int("ten") |
ZeroDivisionError | Division by zero | 8 / 0 |
FileNotFoundError | Missing file in read mode | open("missing.txt") |
KeyError | Missing dictionary key | profile["age"] |
TypeError | Unsupported types or call shape | "4" + 2 |
Reject Invalid Data
Use raise when a function cannot accept the supplied value.
if marks < 0:
raise ValueError("marks cannot be negative")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")File Paths and Modes
A file keeps data after the program finishes. A path identifies the file; a mode controls the permitted operation.
| Mode | Meaning | If the file exists | If missing |
|---|---|---|---|
r | Read text | Open from the beginning | Error |
w | Write text | Replace existing content | Create |
a | Append text | Add at the end | Create |
x | Create exclusively | Error | Create |
b | Binary modifier | Combine with another mode, such as rb | |
A relative path starts from the programβs current working directory. An absolute path begins from the filesystem root.
Reading and Writing Text Files
Use with open(...) so Python closes the file automatically, including when an exception occurs.
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 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")For predictable text handling across systems, production programs commonly pass encoding="utf-8".
Working with CSV
CSV stores records as rows and fields. Pythonβs csv module handles quoting and delimiters safely.
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])Asha,88 Ravi,92
csv.reader() returns each row as a list of strings. Convert numeric fields before calculating with them.
Working with JSON
JSON represents objects, arrays, strings, numbers, booleans and null in a portable text format.
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)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
They hide where names came from and can overwrite existing names.
Handle only failures the program understands and can recover from.
w replaces existing content, while a preserves it and appends.
Use csv and json so quoting, escaping and types are handled correctly.
π Modules, Exceptions & Files β Quick Revision
Review these ten rules before attempting the quiz and programming problems.
A module groups reusable Python code.
module.name keeps a toolβs source clear.
try contains code that may raise an expected exception.
except should name the most specific useful type.
else runs only when try succeeds.
finally runs whether an exception occurs or not.
with open(...) closes a file automatically.
Mode w replaces; mode a appends.
csv.reader() produces rows of strings.
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?
π» 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.
mathImport math, read a radius and display the circle area rounded to two decimal places.
4Expected output: Area = 50.27math.pi * radius ** 2, then pass the result and 2 to round().Python Code Editor
Program Output
Run your program to see the output.
Test Case
import math
radius = float(input())
area = math.pi * radius ** 2
print("Area =", round(area, 2))Read two integers. Display the quotient, or a clear message when the divisor is zero.
18, 0Expected output: Cannot divide by zerotry and catch ZeroDivisionError.Python Code Editor
Program Output
Run your program to see the output.
Test Case
first = int(input())
second = int(input())
try:
print("Quotient =", first // second)
except ZeroDivisionError:
print("Cannot divide by zero")Read notes.txt and display its number of lines and words.
Learn Python\nPractice daily\nBuild projectsExpected output: Lines = 3 and Words = 6splitlines() for lines and split() for words.Python Code Editor
Program Output
Run your program to see the output.
Test Case
with open("notes.txt", "r") as file:
text = file.read()
print("Lines =", len(text.splitlines()))
print("Words =", len(text.split()))Read the three rows in marks.csv and display the whole-number average.
Asha,84 β’ Ravi,90 β’ Mina,96Expected output: Average = 90row[1] to int, add every mark and divide by the row count.Python Code Editor
Program Output
Run your program to see the output.
Test Case
import csv
total = 0
count = 0
with open("marks.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
total += int(row[1])
count += 1
print("Average =", total // count)Load profile.json and display the learnerβs name and number of skills.
{"name":"Bhavya","skills":["Python","C","DSA"]}Expected output: Name = Bhavya and Skills = 3json.load(file), then access the name and skills keys.Python Code Editor
Program Output
Run your program to see the output.
Test Case
import json
with open("profile.json", "r") as file:
profile = json.load(file)
print("Name =", profile["name"])
print("Skills =", len(profile["skills"]))π― Build Programs That Connect and Recover
Reuse tools through namespaces.
Expect realistic failures.
Open safely with with.
Use CSV and JSON libraries.
π¬ Safe File Processing β Visual Flow
Follow one file-processing task from opening the resource to a safe, parsed result.
π How Safe File Processing Works
1. Choose the Path and Mode
Identify the target file and select a mode that matches the intended read, write or append operation.
π Program Tracing β Safe Division
Trace how try transfers control to the matching except block when the divisor is zero.
Click Next to begin tracing.
β
π€ Modules, Exceptions & Files β Interview Questions
Answer aloud before opening each explanation.
What is the difference between a module and a package?
A module is normally one Python file. A package groups related modules inside a directory and exposes them through a package namespace.
Why is import math often clearer than a wildcard import?
Calls such as math.sqrt() reveal the source of a name and avoid silently overwriting names from other modules.
How do else and finally differ in exception handling?
else runs only when the try block succeeds. finally runs whether execution succeeds or raises an exception.
Why should exceptions be caught specifically?
Specific handlers recover from known failures without hiding unrelated bugs or interrupt signals that the program does not understand.
What problem does a context manager solve for files?
It guarantees that the file is closed when the block ends, even if an exception interrupts work inside the block.
What is the difference between json.load() and json.loads()?
json.load() reads JSON from a file object, while json.loads() parses JSON from a string.
π‘ Modules, Exceptions & Files β Extra Tips
- 01
Prefer explicit imports so readers can locate each external name quickly.
- 02
Keep
tryblocks small; include only statements expected to fail together. - 03
Log or display an actionable error message instead of silently ignoring failure.
- 04
Use
withfor 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.
βοΈ Modules, Exceptions & Files β Extra Practice Questions
- Use
math.sqrt()to display the square root of a valid positive number. - Import
statisticswith an alias and calculate a listβs mean. - Catch invalid integer input and ask the user to try again.
- Raise
ValueErrorwhen marks fall outside 0 to 100. - Count uppercase letters stored in a text file.
- Append a dated study note without replacing earlier notes.
- Copy only non-empty lines from one text file to another.
- Read a CSV expense file and display its largest amount.
- Write a dictionary to JSON using an indentation of two spaces.
- 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.
