Function is defined → Function is called → Execution jumps to function → Executes statements →
Here are well-structured Class 12 CBSE Board Exam Notes for Computational Thinking and Returns value
Programming – 2 based on your syllabus:
Scope of a Variable
Computational Thinking and Programming – 2 Local Scope: Variables declared inside a function.
Global Scope: Variables declared outside a function (use `global` keyword to modify inside
1. Revision of Python Topics Covered in Class XI function).
Python Basics: Variables, Data Types, Operators, Conditional Statements, Loops python
Strings, Lists, Tuples, Dictionaries, Sets
Functions, File Handling, Exception Handling `x = 10 # Global variable
def myfunc():
Libraries: NumPy, Pandas (Basic Concepts) global x
x = x + 5
print(x)
myfunc() # Output: 15
2. Functions in Python `
Types of Functions
3. Exception Handling
1. Built-in Functions: Predefined functions like `len()`, `max()`, `print()`, `input()`, `type()`.
2. Functions Defined in Modules: Functions in Python libraries (`math.sqrt()`, `random.randint()`).
Introduction to Exception Handling
3. User-Defined Functions: Functions created by programmers using `def` keyword.
Exception: Runtime error that disrupts program flow (e.g., `ZeroDivisionError`,
Creating User-Defined Functions `FileNotFoundError`).
Exception Handling: Using `try-except-finally` to prevent program crash.
python
`def greet(name):
Handling Exceptions Using `try-except-finally`
return "Hello, " + name + "!"
print(greet("Rahul")) # Output: Hello, Rahul! python
`
`try:
x = int(input("Enter a number: "))
Arguments and Parameters y = 10 / x
print(y)
except ZeroDivisionError:
Positional Parameters: Arguments passed in order. print("Cannot divide by zero!")
Default Parameters: Parameters with default values. except ValueError:
print("Invalid input! Enter a number.")
Keyword Arguments: Arguments passed with parameter names. finally:
Variable-Length Arguments: `*args` (multiple positional arguments), `**kwargs` (multiple print("Execution Completed.")
`
keyword arguments).
Function Returning Values
4. File Handling in Python
python
`def add(a, b): Types of Files
return a + b
print(add(5, 3)) # Output: 8 1. Text File: Stores data in human-readable format (`.txt`, `.csv`).
`
2. Binary File: Stores data in machine-readable format (`.bin`).
3. CSV File: Comma-separated values format for structured data storage.
Flow of Execution of a Function
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/10 Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/10
File Paths `tell()`: Returns current file cursor position.
`seek(offset, from_where)`: Moves file pointer.
Relative Path: File location relative to the program (`data.txt`).
Absolute Path: Complete path of the file (`C:/Users/rahul/Documents/data.txt`).
5. Binary File Handling
Text File Operations
Opening and Closing a Binary File
Opening a Text File (`open()`)
Modes:
Modes:
`rb`, `rb+`, `wb`, `wb+`, `ab`, `ab+`
`r` (Read), `r+` (Read & Write)
`w` (Write), `w+` (Write & Read) Using `pickle` Module
`a` (Append), `a+` (Append & Read)
python
Reading from a Text File
`import pickle
data = {"Name": "Rahul", "Age": 18}
python with open("data.bin", "wb") as f:
pickle.dump(data, f)
`f = open("example.txt", "r") `
print(f.read()) # Reads entire file content
f.close()
` `dump()`: Write data
`load()`: Read data
`read()`:Reads entire file
python
`readline()`:Reads one line
`readlines()`: Reads all lines as a list
`with open("data.bin", "rb") as f:
new_data = pickle.load(f)
Writing/Appending to a Text File print(new_data)
`
python
`f = open("example.txt", "w")
f.write("Hello, Python!")
6. CSV File Handling
f.close()
`
Opening and Closing a CSV File
`write()`: Writes string python
`writelines()`: Writes multiple lines
`import csv
with open("data.csv", "r") as f:
Using `with` Clause (Automatic File Closing) reader = csv.reader(f)
for row in reader:
print(row)
python `
`with open("example.txt", "r") as f:
print(f.read()) Writing Data to a CSV File
`
python
`seek()` and `tell()` Methods
`import csv
with open("data.csv", "w", newline="") as f:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/10 Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/10
writer = csv.writer(f) 🔹 Exception → A runtime error that disrupts normal program flow.
writer.writerow(["Name", "Age"])
🔹 Common Exceptions → , , , etc.
🔹 Exception Handling → Using
writer.writerows([["Rahul", 18], ["Amit", 20]]) `ZeroDivisionError` `ValueError` `FileNotFoundError`
`
to handle errors and prevent program crashes.
`try-except-finally`
2️⃣ Handling Exceptions using `try-except-finally`
7. Data Structure: Stack
python
Stack (LIFO – Last In First Out) `try:
num = int(input("Enter a number: "))
Operations: result = 10 / num
print(result)
except ZeroDivisionError:
Push: Insert element print("Error: Cannot divide by zero!")
Pop: Remove element except ValueError:
print("Error: Enter a valid number!")
finally:
Implementation Using List print("Execution Completed.") # Runs whether an error occurs or not
`
python
`stack = []
# Push operation 📌 File Handling
1️⃣ Introduction to Files
stack.append(10)
stack.append(20)
stack.append(30)
print(stack) # Output: [10, 20, 30]
# Pop operation 📂 File → A storage unit to store data permanently.
stack.pop()
📄 Types of Files:
✔ Text File ( ) → Stores plain text data.
print(stack) # Output: [10, 20]
`
✔ Binary File ( ) → Stores data in binary format.
`.txt`
✔ CSV File ( ) → Stores tabular data in comma-separated format.
`.bin`
`.csv`
Important Exam Tips 📍 File Paths:
✔️ Understand the concepts deeply: Functions, Exception Handling, File Handling, and Stack. 🔹 Relative Path → (File in the same directory).
🔹 Absolute Path →
`data.txt`
✔️ Practice Python coding regularly. `"C:/Users/Rahul/Documents/data.txt"` (Full file path).
✔️ Learn syntax and file handling operations.
✔️ Solve previous year CBSE board questions.
✔️ Revise CSV and Binary File Handling properly.
2️⃣ Text File Handling
Opening a Text File (`open()`)
These notes cover all key concepts concisely for Class 12 CBSE Board Exam. Let me know if you need
sample questions or programs for practice! 😊 python
Here are concise, easy-to-understand, and pointwise notes for Class 12 CBSE Board Exam on `f = open("file.txt", "r") # Open file in read mode
print(f.read()) # Read entire file content
Exception Handling, File Handling, and Stack in Python, including code snippets for better f.close() # Close the file
understanding. `
📌 Exception Handling 📌 Modes in `open()`:
1️⃣ What is Exception Handling?
`r` → Read
`r+` → Read & Write
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/10 Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/10
→ Write (Overwrites existing content) 📌 Binary File Operations:
✔ Opening & Closing a Binary File
`w`
`w+` → Write & Read
`a` → Append ✔ Reading & Writing using Module
✔ Updating, Searching, and Appending Data
`pickle`
`a+` → Append & Read
Using `pickle` Module
Reading a Text File
python
python
`import pickle
`f = open("file.txt", "r") data = {"name": "Rahul", "age": 18}
print(f.readline()) # Reads one line
print(f.readlines()) # Reads all lines as a list # Writing data to binary file
f.close() with open("data.bin", "wb") as f:
` pickle.dump(data, f)
# Reading data from binary file
with open("data.bin", "rb") as f:
Writing & Appending to a Text File new_data = pickle.load(f)
print(new_data) # Output: {'name': 'Rahul', 'age': 18}
python `
`f = open("file.txt", "w")
f.write("Hello, World!\n") # Writes a string to the file
📌 Binary File Open Modes:
f.writelines(["Line 1\n", "Line 2\n"]) # Writes multiple lines
f.close() `rb` → Read Binary
` `rb+` → Read & Write Binary
`wb` → Write Binary (Overwrites)
`wb+` → Write & Read Binary
Using `with` Clause (Automatic Closing)
`ab` → Append Binary
4️⃣ CSV File Handling
python
`with open("file.txt", "r") as f:
content = f.read()
`
print(content) # File closes automatically
📌 CSV (Comma-Separated Values) File → Used to store tabular data.
📌 Requires Module to handle CSV files.
`csv`
`seek()` and `tell()` Methods Writing to a CSV File
`tell()` → Returns current cursor position. python
`seek(offset, from_where)` → Moves cursor to the specified position.
`import csv
with open("data.csv", "w", newline="") as f:
python
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
`f = open("file.txt", "r") writer.writerows([["Rahul", 18], ["Amit", 20]])
print(f.tell()) # Get current position `
f.seek(5) # Move to 5th character
print(f.read()) # Read from 5th character onwards
f.close()
` Reading from a CSV File
3️⃣ Binary File Handling
python
`import csv
with open("data.csv", "r") as f:
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/10 Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/10
reader = csv.reader(f) ✅ Exception Handling: Use to handle errors.
✅ Text File Handling: Open, Read, Write, Append,
`try-except-finally`
for row in reader:
`seek()` `tell()`.
,
✅ Binary File Handling: Use
print(row) # Output: ['Name', 'Age'], ['Rahul', '18'], ['Amit', '20']
`
module ( , ).
✅ CSV File Handling: Use module (
`pickle` `dump()` `load()`
, ).
✅ Stack Implementation: Use list (
`csv` `writer()` `reader()`
📌 Data Structure: Stack , ).
`append()` `pop()`
📌 Stack (LIFO - Last In First Out) 📌 Exam Tips
✔ Push → Insert element ✔ Practice file handling operations (open, read, write, append).
✔ Pop → Remove element ✔ Understand properly with examples.
✔ Work on stacks with different operations.
`try-except-finally`
1️⃣ Implementing Stack using List ✔ Write & execute Python programs to check outputs.
✔ Solve CBSE sample papers & previous year questions.
python
These notes are simple, pointwise, and exam-focused with easy-to-understand code snippets. Let
`stack = [] me know if you need sample questions or additional explanations! 😊🔥
# Push Operation
stack.append(10)
stack.append(20)
stack.append(30)
print(stack) # Output: [10, 20, 30]
# Pop Operation
stack.pop()
print(stack) # Output: [10, 20]
`
2️⃣ Implementing Stack using Functions
python
`stack = []
def push(element):
stack.append(element)
print(f"Pushed {element} into stack")
def pop():
if len(stack) == 0:
print("Stack is empty!")
else:
print(f"Popped {stack.pop()} from stack")
push(10)
push(20)
pop() # Output: Popped 20 from stack
print(stack) # Output: [10]
`
📌 Quick Revision Points
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/10 Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/10