Teaching Guide - Class 12 Computer Science (Python) - Sumita Arora (Chapters 1-5)
Teaching Guide - Class 12 Computer Science (Python) - Sumita Arora (Chapters 1-5)
Key Concepts
• Tokens and Syntax: A token is the smallest unit of code, such as keywords, identifiers, literals,
operators, and delimiters 1 . For example, in x = int(input("Enter number")) , tokens
include x , = , int , ( , input , "Enter number" , and so on 2 . The Python interpreter
converts source code into tokens to parse the program.
• Identifiers and Keywords: Identifiers are user-defined names (variable, function names, etc.), while
keywords (like if , for , while , import , None , etc.) are reserved words with special meaning
3 . Identifiers must start with a letter or underscore and cannot be keywords.
• Data Types and Literals: Core data types include integers, floats, strings, and booleans. Literals are
fixed values in code: string literals ( "hello" ), numeric literals ( 5 , 3.14 ), boolean literals
( True , False ), special literal None , and collection literals (lists, tuples, etc.) 4 .
• Variables and Assignment: Python uses implicit declaration: a variable is created when first
assigned a value, and its type is determined at runtime 5 . E.g., x = 5 makes x an integer. The
= operator assigns values; using = in a conditional (instead of == ) is a common mistake.
• Expressions and Statements: An expression is a combination of values and operators that produces
a value (e.g. 2+3 , a > b ), while a statement is an instruction (e.g. print("Hello") , a = 5 )
6 . A program consists of statements that may contain expressions.
• Operator Precedence: Python follows standard precedence rules (parentheses, exponent ** , then
multiplication/division/modulo, then addition/subtraction, etc.). For example, 14 + 13 % 15 is
evaluated as 14 + (13 % 15) = 27, not (14 + 13) % 15 7 .
• Input/Output: Use input() to read a string from the user (convert to int/float if needed) and
print() to output. E.g.:
• Flow Control – Conditionals: Use if , elif , and else for decision-making. Indentation defines
the block. Example:
1
else:
print("Grade C")
• Loops:
• while loop: Repeats as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1
for i in range(5):
print(i)
• Comments and Indentation: Comments begin with # and are ignored by the interpreter. Python
uses indentation (tabs or spaces) to define code blocks. Mismatched indentations cause errors.
• Token: The smallest unit in Python source (keyword, identifier, literal, operator, etc.) 1 . Tokens are
building blocks of the code.
• Keyword: A reserved word in Python that has a special meaning to the interpreter (e.g., if ,
while , for , import , None ) 3 .
• Identifier: A user-defined name for variables, functions, classes, etc. Must start with a letter/
underscore and not be a keyword 3 .
• Literal: A fixed value in code. Types include string literal ( "abc" ), numeric literal ( 5 , 3.14 ),
boolean literal ( True , False ), None , and collection literals (e.g. list literal [1,2,3] ) 4 .
• Expression: A combination of values and operators that yields a value (e.g. a + b , x % 2 == 0 ).
• Statement: A complete instruction like assignment or function call (e.g. a = b + 2 , print(x) ).
• Operator Types: Arithmetic ( + - * / % ** // ), Relational ( == != > < >= <= ), Logical ( and ,
or , not ), Assignment ( =, +=, -=, ... ), Membership ( in , not in ), Identity ( is ,
is not ) 8 9 .
• Mutable vs Immutable: (Introduced later) Lists are mutable (elements can be changed in place)
while strings, tuples are immutable (cannot change once created) 10 11 .
Code Examples
# If-else example
2
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
• Syntax Errors: Forgetting a colon after if , for , while , or def leads to errors. Example:
if x > 0 print(x) missing colon.
• Indentation Errors: Mixing tabs and spaces or wrong indent level causes errors. Each block must be
consistently indented.
• Invalid Identifiers: Names starting with a digit ( 2nd_var ) or containing special chars
( price*qty ) are invalid. Also, using a keyword as a name (e.g. for = 5 ) is invalid 12 .
• Assignment vs Comparison: Using = instead of == in conditions (e.g. if x = 5: ) is an error.
• Type Errors: Mixing types without conversion. For example, print("Sum:", 5 + "10") causes a
type error because int and str cannot be added directly.
• Infinite Loops: A while loop with a condition that never becomes false (e.g. not updating the loop
variable) causes a hang. Example: while x < 50: print(x) with no update is infinite 13 .
• Off-by-One in Loops: Common mistakes in range() . For instance, range(1,10) goes from 1 to
9, not including 10 14 .
• Q: What is a token in Python? A: The smallest unit (keyword, identifier, literal, operator, etc.) in a
Python program 1 .
• Q: How do keywords differ from identifiers? A: Keywords are reserved by Python and have special
meaning (e.g. if , while ), whereas identifiers are user-defined names for variables, functions,
etc. Identifiers cannot be keywords 3 .
• Q: What are literals? A: Data items with fixed values (e.g. "hello" , 42 , True , None ). Python
supports string, numeric, boolean, None , and collection literals 4 .
• Q: True or False: “Variable declaration is explicit in Python.” A: False. Python uses implicit declaration –
variables are created when first assigned 5 .
3
• Q: Define an expression vs a statement. A: An expression yields a value (like a + b ), while a
statement performs an action (like print(a) or a = 5 ) 6 .
• Q: Name four core data types in Python. A: int , float , str , bool (others include list ,
tuple , dict , set ).
• Q: What is the output of print(14 + 13 % 15) and why? A: 27, because % (modulo) has higher
precedence than + 7 .
Key Concepts
• Strings: Immutable sequences of characters. Support indexing and slicing. Python uses 0-based
and negative indexing (two-way indexing) 15 , e.g., s = "python"; s[0] == 'p'; s[-1] ==
'n' . Slicing s[i:j] gives substring from index i up to j-1. Example: "python"[1:4] yields
"yth" .
• String Operations:
• Concatenation: + , e.g. "Hello " + "World" .
• Repetition: * , e.g. "ab"*3 → "ababab" .
• Length: len(s) gives number of characters.
• Membership: 'a' in s checks if a character/substring exists.
4
• Common Methods: s.lower() , s.upper() , s.strip() , s.split() , s.find() ,
s.replace(old, new) . Note string methods return a new string (strings are immutable). For
example, " hello ".strip() → "hello" .
• Lists: Mutable sequences that can store heterogeneous items. Defined with square brackets, e.g.
lst = [8, 9, 10] . Elements accessed by index ( lst[0] ).
• List Operations:
• Indexing/Slicing: Same rules as strings.
• Common Methods:
◦ append(x) : add one element at end.
◦ extend([a,b]) : add multiple elements.
◦ insert(i, x) : insert at index.
◦ pop(i) : remove and return element at index (default last).
◦ remove(x) : remove first occurrence of value.
◦ sort() : sort list in place.
◦ reverse() : reverse list in place.
Example (from [20] Q5):
• Mutability: Lists are mutable (elements can be changed in place) 10 , whereas strings are immutable.
For example, assigning to a string index raises an error. Understanding “in-place” means the original
object is modified rather than creating a new one 11 .
• Tuples (brief): Immutable sequences, similar to lists but fixed after creation. Useful as keys in
dictionaries. ( (1,2,3) ). Not covered in depth here, but mention immutability contrast with lists.
• Sequence: An ordered collection of elements (strings, lists, tuples). Supports indexing and slicing.
• Indexing: Accessing an element by its position, e.g. s[i] . Python allows negative indexing
( s[-1] is last element).
• Slicing: Accessing a sub-part of a sequence: s[i:j] returns elements from index i up to j-1.
Omitting i or j defaults to start/end. Example: "computer"[2:] → "mputer" .
• Mutable: An object that can be changed after creation (e.g. lists) 10 .
• Immutable: An object that cannot be changed after creation (e.g. strings, tuples).
• Append vs Extend:
• append(x) adds a single element to end.
• extend([a,b]) adds each element of the list to the end. For instance, [1,2].append([3,4]) gives
[1,2,[3,4]] , whereas [1,2].extend([3,4]) gives [1,2,3,4] . 16
• Pop vs Remove:
• pop(i) removes and returns element at index i.
5
• remove(x) removes first occurrence of value x.
Code Examples
# Slicing example
nums = list(range(1, 11))
print(nums[1:5]) # prints [2, 3, 4, 5]
print(nums[:3]) # prints [1, 2, 3]
print(nums[7:]) # prints [8, 9, 10]
• Index Errors: Accessing an index out of range raises an IndexError . E.g., "abc"[5] fails.
Emphasize checking len() before indexing.
• Immutable Misunderstanding: Attempting s[0] = 'x' on a string or t[1] = 5 on a tuple
causes errors. Students may expect strings to behave like lists; clarify that strings cannot be changed
in place.
6
• Using append vs extend : Confusing the two methods leads to nested lists. For example,
lst.append([4,5]) adds a sublist, not two elements.
• Off-by-One in Slicing: Remember slicing’s end index is exclusive. "abcd"[1:3] yields "bc" , not
"bcd" .
• Looping on Mutable Sequences: Be cautious when modifying a list while iterating over it (can skip
elements or cause unexpected behavior).
• Copy vs Reference: Assigning one list to another name (e.g. a = [1,2]; b = a ) creates a
reference, not a copy. Changing b will change a . Teach using b = a.copy() if needed.
• Q: Explain string slicing. A: s[i:j] returns a substring from index i up to j-1. Omitting i or j
means start/end. Negative indices count from end. E.g. "computer"[1:-1] → "compute" .
• Q: How are lists and tuples different? A: Lists are mutable sequences; tuples are immutable. Lists use
[...] , tuples use (...) . Tuples can be keys in dicts, lists cannot 17 .
• Q: What is the difference between append() and extend() on lists? A: append(x) adds x as a
single element; extend([a,b]) adds each element of the iterable. Thus, lst.append([4,5])
makes a sublist, while lst.extend([4,5]) adds 4 and 5 separately 16 .
• Q: What does it mean that lists are mutable? A: Their elements can be changed in place without
creating a new list. E.g., lst[0] = 10 alters the same list object 10 .
• Q: Give an example of an infinite loop using string/list. A: (E.g.) s = "hello"; i=0; while i <
len(s): print(s); with no increment of i – it will print forever.
• Visualize Sequences: Use arrows or highlight indices on the board to show how slicing works. For
negative indexing, illustrate counting from the right.
• Hands-On Demonstration: Let students experiment with Python’s interactive shell. For example,
type s = "hello"; print(s[1:4]) and see results.
• Concrete Exercises: Give small puzzles (like the two-character-per-line string traversal from [20])
and walk through them.
• Emphasize Immutability: Demonstrate trying to change a string (and catching the error) versus
changing a list. Show id() of a list before/after changes to illustrate same object.
• Link to Real-World: Compare a list to a resizable array or a shopping list (you can add/remove
items) and a string to an unchangeable message on a board.
7
Chapter 3: Working with Functions
Key Concepts
• Functions: Reusable blocks of code that perform a specific task. Defined with def keyword. They
improve modularity and readability 18 . A program with functions is easier to manage because each
function handles one part of the problem 18 .
• Function Syntax:
def function_name(parameters):
"""Optional docstring."""
# statements
return value
8
• Module-defined: In imported modules. E.g. math.sqrt() , random.randint() . Require
importing the appropriate module first.
• Function: A named block of code designed to perform a specific task. Enhances code reuse and
readability 18 .
• Function Header: The first line def fname(params): . It tells you the function’s name and its
parameters 27 .
• Parameter: A named variable in a function definition that receives a value. (e.g. in def
add(a,b): , a and b are parameters) 21 .
• Argument: The actual value passed to a function’s parameter when calling it (e.g. in add(2,3) , 2
and 3 are arguments) 21 .
• Default Argument: A parameter with a default value (e.g. def f(x, y=5): ). If omitted in the call,
the default is used 22 .
• Keyword Argument: An argument passed by explicitly naming the parameter (e.g. f(y=10,
x=2) ). Allows any order.
• Fruitful (Value-returning) Function: Returns a value using return .
• Void (Non-fruitful) Function: Doesn’t return a value (implicitly returns None ). Used for actions like
printing.
• Scope: The region of code where a variable is accessible. Local scope (inside functions) vs global
scope (module level) 28 .
Code Examples
9
# Global vs Local example
count = 0
def increment():
global count
count += 1
increment()
print(count) # Output: 1
x = 5 # global variable
f()
print("Outside f, x =", x)
# Outputs: Inside f, x = 10
# Outside f, x = 5
• Missing Colon/Indent: Forgetting the colon after def or improper indentation leads to syntax
errors.
• Name Errors: Calling a function or using a variable that doesn’t exist (e.g. typo in name) causes
NameError .
• Parameter Mismatch: Providing wrong number of arguments (too many or too few) causes errors.
• Mutable Default Pitfall (advanced): If a default parameter is a mutable object (like a list), it persists
across calls. (Not typically in NCERT scope, but worth a caution: prefer immutable defaults.)
• Not Returning: Forgetting a return statement (or indenting it wrongly) can cause the function to
return None .
• Using global Improperly: Forgetting global when needed will create a new local variable
instead of modifying the global. Conversely, overusing global can make code hard to debug 24 .
• Infinite Recursion: (If recursion were covered) A function calling itself without a base case leads to
crash/stack overflow. Not in this chapter but warn if mentioned.
• Q: Why are multiple functions considered better design than a single large program? A: Functions
break the program into logical parts, making it easier to handle, reduce size of each block, and
improve readability and manageability 18 .
• Q: What information does a function header provide? A: The function header (e.g.
def f(a, b=5): ) tells us the function’s name ( f ) and its parameters ( a , b ) 27 .
• Q: Define arguments and parameters. A: Parameters are named variables in the definition
(placeholders). Arguments are the actual values passed in a call. They are related: each argument
value is received by the corresponding parameter 21 . Example: in f(x=3, y=4) , x,y are
params, 3,4 are args.
10
• Q: What is the default return value of a function with no return ? A: None 19 (demonstrated in
MCQ: no explicit return yields None ).
• Q: Explain local vs global variables. A: A local variable is defined inside a function and only exists
during that function call. A global variable is defined outside any function and can be accessed
everywhere (unless shadowed) 28 .
• Q: What does global do and why is it discouraged? A: global var inside a function tells Python
to use the global variable var instead of creating a local one. It’s discouraged because it makes
tracking variable changes harder and can lead to bugs 24 .
• Q: Name and describe one style of function. A: Built-in function – predefined in Python (e.g. len() ,
input() ). User-defined function – defined by programmer using def . Module function – defined in
an imported module (e.g. math.sqrt ).
• Q: When would you use default arguments? A: When you want a function parameter to have a value
even if the caller doesn’t provide it, making the argument optional 22 .
• Q: What is a fruitful vs a non-fruitful function? A: A fruitful function returns a value (using return ).
A non-fruitful (void) function does not return a meaningful value (implicitly returns None ) 29 .
• Function Analogy: Describe a function like a “mini-program” or a vending machine: give it inputs, it
does work, and gives an output. This shows modular design.
• Stack Visualization: Draw how function calls stack up (first-in, last-out). Show how each function has
its own local variables.
• Trace Code Execution: Walk through a call step-by-step (possibly on a flowchart). Example: trace
what happens when f(3) is called.
• Demonstrate Scope: Use examples to show that changing a local variable inside a function doesn’t
affect the global one of the same name (without global keyword).
• Default and Keyword: Show an example like def f(a, b=2, c=3): , then call with different
orders, to demonstrate flexibility.
• Use Built-ins First: Encourage using Python’s built-in functions (e.g. sum() , min() , max() )
before writing custom ones.
• Reinforce Reusability: Show how writing a function once allows multiple calls (e.g. a
max_of_three function can be used on different lists).
11
Chapter 4: Using Python Libraries
Key Concepts
• Modules: A module is a file ( .py ) containing variables, functions, classes, etc., related to a
particular task. It can be imported and reused in other programs 30 . For example, math.py is a
module providing mathematical functions.
• Packages: A package is a collection of modules organized under a directory with an __init__.py
file 31 . A package groups related modules under a common namespace. The __init__.py file
(can be empty) signals to Python that the directory should be treated as a package 32 .
• Libraries: A library is a collection of modules/packages that serve a common purpose (e.g. the
Python Standard Library for general tasks, or NumPy for numerical computing) 33 34 . Libraries can
be built-in or third-party.
• Importing Modules:
• import module : Imports the module and creates a namespace. Use functions as
module.func() .
• from module import obj : Imports specific function/class into current namespace (no prefix
needed).
• from module import * : Imports all public names, but is discouraged due to namespace
pollution.
• Wildcard Import: from pkg import * imports all modules from package. Example: from
mypackage import * (module files must be listed in __all__ or __init__.py ). The *
operator is used for wildcard imports 35 .
• Module Search Path (PYTHONPATH): When importing, Python searches in the following order:
• Built-in modules (like sys , math ).
• Directories in the environment variable PYTHONPATH or in sys.path (includes the current
directory, site-packages, etc.) 36 .
To make your own libraries accessible, place them in the site-packages directory or adjust
PYTHONPATH 37 .
• Docstrings: Modules, functions, and classes can have triple-quoted string docstrings right after their
definition. Docstrings are used for documentation and are shown by help() . They should describe
what the code does 38 .
• Standard Library Examples: Common libraries include math (mathematical functions), random
(random number generation), datetime (date/time operations), sys (system-specific
parameters). To use them, one must import math etc.
• CSV Files: Python has a csv module to read/write CSV (Comma Separated Values) files (tabular
text). CSV stands for Comma Separated Values. TSV is Tab Separated Values 39 .
• File Extensions: Python modules have .py extension 40 . Packages are directories with
__init__.py .
• Module: A file containing Python definitions. E.g., a file tempConv.py with conversion functions is
a module 41 .
• Package: A directory of modules with __init__.py . It allows hierarchical organization (e.g.
mypackage.myfile ).
• Library: A collection of related modules/packages for a broad purpose (e.g. Standard Library).
12
• Import: The process of making a module’s contents accessible. import math loads the math
module. from math import sqrt imports only the sqrt function. The import statement
adds names to the current namespace in two ways:
• import module adds the module’s name (you use module.name ).
• from module import obj adds the object name directly (no prefix needed) 42 .
• __init__.py : Indicates that a directory is a Python package. Even if empty, its presence is
required for imports from that directory to work 32 .
• Docstring: A triple-quoted string literal that provides documentation. Placed at the top of modules,
classes, or functions. Python’s help() displays docstrings 38 .
• PYTHONPATH: An environment variable (or sys.path list) that tells Python where to look for
modules/packages 36 .
• Namespaces: Each module creates its own namespace. Importing with import module keeps its
names in that namespace, while from module import * dumps all names into the current
namespace (careful!).
Code Examples
13
reader = csv.reader(f)
for row in reader:
print(row)
• ModuleNotFoundError: Happens when trying to import a module that Python cannot find. Check
spelling, installation ( pip install if needed), or whether it’s in the right directory (or in
PYTHONPATH ).
• Name Shadowing: Naming your script the same as a standard module (e.g. math.py ) will cause
imports to use the wrong file. Always avoid name collisions.
• Using from module import * : This can overwrite existing names without warning. It’s better to
import only needed names or use the module prefix.
• Missing __init__.py : Forgetting the __init__.py file in a package directory will make
imports fail (Python won’t recognize it as a package) 32 .
• Global vs. Module Names: Variables defined in a module are global to that module, not to the
whole program unless imported with from . Using import module requires referencing via
module.var . A common confusion is where a variable is actually defined and accessed.
• Forgetting to Save Modules: If you create a new module file, ensure you save it in the working
directory before importing.
• Q: What is a module? A: A .py file containing related functions, classes, and variables which can be
imported into other programs 30 .
• Q: What is a package? A: A directory of Python modules containing an __init__.py . It groups
modules under one namespace 31 .
• Q: How is a library different from a module? A: A library is a collection of modules/packages (e.g. the
Standard Library). A module is a single file.
• Q: Why do we use __init__.py in a package? A: It tells Python the directory is a package; without
it, imports from that folder won’t work 32 .
• Q: What is a docstring? A: A documentation string in triple quotes right after a module/function/
class definition. It describes what the code does and is shown by help() 38 .
• Q: Explain the difference between import module and from module import name . A:
import module creates a new namespace ( module.name needed). from module import
name brings name directly into current namespace (no prefix needed) 42 .
• Q: What does PYTHONPATH do? A: It’s an environment variable (or a list of directories) that Python
searches when importing modules. Adding directories to PYTHONPATH lets Python find modules
there 36 .
• Q: Give an example of a built-in library function. A: len() , print() , math.sqrt() ,
random.randint() , etc.
• Example Exercise: “Create a module tempconv.py with functions to convert temperature between
Celsius and Fahrenheit, then use it in a program.”
14
• Approach: Write the functions and docstrings in tempconv.py . In the main program, use
import tempconv and call tempconv.to_celsius(77) . Test with known values (e.g., 32°F =
0°C).
• Example Exercise: “Use the random module to simulate rolling two dice 100 times and count the
number of times they show doubles.”
• Approach: Import randint from random , loop 100 times, generate two numbers between 1 and
6, compare them, and count matches.
• Exercise Tips: Stress that the solution often involves finding and using the right module/function.
Teach students to consult Python’s documentation or help() to understand module functions and
parameters.
• Demonstrate Imports: Show live examples. For instance, open a Python REPL, type import math
and try math.sqrt(16) . Then explain what math and sqrt are.
• Docstrings in Action: Create a small module with docstrings and use help(module) to show how
the documentation appears. Highlight how docstrings aid understanding 38 .
• Namespace Visualization: Draw how module.name refers to something. For example, explain
why after import math , you use math.pi , not just pi .
• Explain sys.path : Briefly show import sys; print(sys.path) in class, and highlight
common entries (like current directory, site-packages). Explain why modules must be on this path.
• Package Example: If possible, make a simple package directory on the fly, add an __init__.py ,
and import. This concrete example helps demystify packages.
• Highlight Standard Libraries: Mention that Python comes with a rich library; encourage
exploration. For example, challenge: “Use the datetime module to print today’s date.”
• Caution on Third-Party Modules: Mention that some libraries (like NumPy) require separate
installation via pip, unlike built-ins. Ensure students know how to use pip if needed.
Key Concepts
• Files: A file is data stored on disk under a name. It may contain text or binary data. Working with files
lets programs read input that persists beyond program run and save output.
• Opening Files: Use open(filename, mode) to open a file. The mode specifies the operations
permitted (read, write, append, binary/text) 43 . Common modes include:
• 'r' : Read text (default).
• 'w' : Write text (truncates file if exists).
• 'a' : Append text (adds to end).
• 'r+' : Read/write (text), no truncation.
• Prefixing with 'b' (e.g. 'rb' ) opens in binary mode (no translation of newline).
Modes that do not lose existing data: 'rb' , 'ab' , 'a+b' , 'r+' 43 .
• Closing Files: Always close a file after use ( file.close() ) or better use a with statement
(context manager) which auto-closes. Example: with open("file.txt", "r") as f: ... .
• Text vs Binary Files:
15
• Text Files: Store data as human-readable characters (ASCII/Unicode) with end-of-line characters.
Reading a text file may perform newline translations (e.g. on Windows) 44 .
• Binary Files: Store data as raw bytes (e.g. images, audio). They are read/written byte-for-byte, no
encoding translation 44 . Text mode vs binary mode affects how data is returned and written.
• Reading from Files: After opening in read mode:
• read() : Reads entire file as one string.
• read(n) : Reads up to n characters.
• readline() : Reads the next line (ending at \n ), returns it as a string 45 .
• readlines() : Reads all lines into a list of strings (one per line). This returns a list 45 .
• (In Python 3, reading text returns str ; in binary mode, bytes .) For CSV or structured data, use
the csv module’s reader.
• Writing to Files: After opening in write/append mode:
• write(string) : Writes the string to the file (does not add newline automatically). Returns
number of characters written.
• writelines(list_of_strings) : Writes a list of strings to the file. Don’t forget to include
newline characters if needed.
• Pointer and Modes: The file pointer indicates where reading/writing starts. In append mode ( 'a'
or 'a+' ), pointer is at end, so writes append. In read mode, pointer starts at beginning.
• Specialized File Types:
• CSV Files: Use import csv . Use csv.reader() to parse CSV, and csv.writer() /
writerow() to write. CSV uses comma (or other delimiter) to separate values 46 .
• Pickle (Binary): For saving Python objects, use pickle.dump(obj, file) and
pickle.load(file) for binary files (not text). (If in curriculum, mention briefly.)
• Error Handling: Opening a nonexistent file in read mode raises FileNotFoundError . Always
handle this in production code (e.g. with try/except ).
• Text File: Contains readable characters; lines end with newline characters. Each \n may be
translated depending on OS 44 .
• Binary File: Contains raw bytes. Example: images, audio files. Python reads/writes exactly the bytes,
with no translation 44 .
• CSV (Comma Separated Values): A text file format where each line is a record and fields are
separated by commas 47 . Rows correspond to lines; columns to values. TSV is similar but tab-
separated.
• File Modes: The second argument to open() . E.g., 'r' , 'w' , 'a' , plus 'b' for binary (e.g.
'rb' , 'wb' ). Mode determines read/write/appending behavior.
• EOF (End of File): A special marker for the end. Functions like read() return an empty string ''
when at EOF.
• Pointer (Cursor): Position in the file. Reading functions ( readline() , etc.) advance the pointer.
seek() can move it.
• Newline ( \n ): End-of-line character in text files. Methods like strip() / rstrip() can remove it
from lines. For example, line = f.readline().rstrip('\n') .
16
Code Examples
# CSV example
import csv
rows = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]
with open("people.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(rows)
17
Common Errors and Misconceptions
• Forgetting to Close File: Always close files, or better use with to auto-close. Not closing can lead
to data not being written (especially in write mode).
• Mode Mistake: Opening a file in write mode 'w' erases existing content. Use 'a' to preserve
data (append) 43 . Example: open("file.txt","w") clears the file.
• Wrong Mode: Using text mode when binary is needed (or vice versa) can cause data corruption or
TypeError (e.g. writing a string to a binary file).
• Infinite Reading: Looping with while True: line = f.readline() without break at EOF will
loop infinitely. Use for line in f: or check for empty string to stop.
• Trailing Newlines: Students often get extra blank lines when printing lines with print() (because
print adds its own newline). Recommend using print(line, end="") or line.strip() .
• CSV Peculiarities: When using csv module on Windows, include newline="" in open() to
avoid blank lines between rows. Also ensure proper quoting if fields contain commas.
• File Paths: Be aware of current working directory. Opening "data.txt" looks in the script’s
working directory. To be safe, show how to use full paths or os.path .
• Q: What are text files and binary files? A: Text files store characters with a newline delimiter; reading
them may transform newline characters 44 . Binary files store raw bytes (e.g. images, pickles) and
have no special encoding/decoding 44 .
• Q: Name functions to read/write text files. A: To read: read() , readline() , readlines() 48 .
To write: write() and writelines() 48 .
• Q: Name functions to read/write CSV files. A: Use the csv module: csv.reader() to read, and
csv.writer() (with .writerow() / .writerows() ) to write 46 .
• Q: What does CSV stand for? A: Comma Separated Values. TSV stands for Tab Separated Values 49 .
• Q: In which mode do you open a file to append without losing data? A: 'a' (append) or 'a+'
(read+append) 43 . ‘rb’ , ‘ab’ , ‘a+b’ , and ‘r+’ modes also preserve existing data 43 .
• Q: What is the default return type of f.read() on a text file? A: A string (of type str ) 50 . On a
binary file, it would be bytes .
• Q: What does readlines() return? A: A list of strings, each element being one line including the
newline character 50 .
• Q: Describe the with statement for files. A: with open(...) as f: opens a file and ensures
it’s automatically closed when the block ends, even if errors occur. It’s the recommended way to
handle files.
• Example Exercise: “Write a program to count the number of lines in a text file.”
• Approach: Use with open("file.txt","r") as f: and loop:
count = sum(1 for line in f) . Emphasize reading line by line. Handle
FileNotFoundError in case the file doesn’t exist.
• Example Exercise: “Append a list of numbers to a file, then read and compute their sum.”
• Approach: Write numbers (with newlines) using write() . Then reopen file in read mode, read
lines, convert each to int, and sum. Teach stripping newline and int() conversion.
18
• Exercise Tips: For file operations, always plan: open file, perform actions, close file. For reading
exercises, encourage thinking about whether to read all at once ( read() ) or line by line
( readline() or iterating).
• Use Real Files: Demonstrate by opening a text file (like a .txt of your choice) and reading it in
class. Show its contents before/after.
• Word Processor Misconception: Remind students that writing print("Hello") doesn’t
automatically save to a file – they must explicitly open and write.
• EOF Illustration: Show that reading past the end returns '' or stops a loop. For example,
line = f.readline() after last line returns an empty string.
• CSV Demo: If possible, show the CSV file created (maybe open it in a text editor or Excel) to
emphasize the comma separation.
• Binary vs Text: Compare writing a simple text file vs writing binary (like pickling a dict) to highlight
the difference.
• Catching Errors: Introduce simple try/except around file open to catch missing file errors,
reinforcing good practice.
• Link to Real Data: Use a small real dataset (like names/grades CSV) to make file handling engaging.
Sources: Reliable educational resources and official documentation were used to compile this guide 1 3
4 10 11 6 41 38 44 (citations indicate specific references). All code examples and teaching
strategies are original or adapted for clarity.
Science with Python by Sumita Arora for Class 12 CBSE & NCERT | KnowledgeBoat
https://www.knowledgeboat.com/learn/sumita-arora-python-computer-science-class-12-cbse/solutions/BbYbr0/functions
10 11 15 Chapter 2: Python Revision Tour II | Solutions of Computer Science with Python by Sumita
16 17
with Python by Sumita Arora for Class 12 CBSE & NCERT | KnowledgeBoat
https://www.knowledgeboat.com/learn/sumita-arora-python-computer-science-class-12-cbse/solutions/BMdBaB/python-libraries
19
39 43 44 45 46 47 48 49 50 Chapter 5: File Handling | Solutions of Computer Science with Python by
20