Class XII Computer Science – Unit 1: Computational Thinking and Programming – 2 | 50 Practice Questions
Class 12 · Computer Science
Class XII Computer Science — Unit 1
Computational Thinking and Programming – 2
Complete Unit Coverage
- Functions — built-in, module and user-defined functions, parameters, arguments, return values and scope
- Exception Handling — exceptions, try, except, else and finally
- Text File Handling — opening, reading, writing, appending and file methods
- Binary File Handling — pickle module, dump() and load()
- CSV File Handling — csv module, reader(), writer(), writerow() and writerows()
- Stack — LIFO principle and implementation using Python lists
Section A — Very Short Answer Questions
Q1. What is a function in Python?
Answer: A function is a named block of reusable code designed to perform a specific task.
Explanation: Functions improve code reusability, modularity and readability.
Q2. State True or False: A function can return more than one value.
Answer: True.
Explanation: Python can return multiple values by packing them into a tuple.
def calc(a, b):
return a + b, a * b
Q3. What is a formal parameter?
Answer: A formal parameter is a variable specified in the function definition that receives a value when the function is called.
Explanation: In def add(a, b):, a and b are formal parameters.
Q4. What is an actual parameter?
Answer: An actual parameter is the actual value or expression passed to a function during its call.
Example: In add(10, 20), 10 and 20 are actual parameters.
Q5. What is the purpose of the return statement?
Answer: The return statement sends a value or result back to the calling statement.
Explanation: It also terminates the execution of the function at that point.
Q6. What is the scope of a variable declared inside a function?
Answer: It has local scope.
Explanation: A local variable can normally be accessed only within the function in which it is created.
Q7. Which keyword is used to modify a global variable inside a function?
Answer: The global keyword.
Example:
x = 10
def change():
global x
x = 20
Q8. What is an exception?
Answer: An exception is an error or unexpected event that occurs during program execution and disrupts the normal flow of the program.
Q9. Which block is used to handle an exception?
Answer: The except block is used to handle an exception.
Q10. Which block executes whether an exception occurs or not?
Answer: The finally block.
Explanation: It is commonly used for cleanup operations such as closing files.
Q11. Which exception occurs when a file opened in r mode does not exist?
Answer: FileNotFoundError.
Q12. Which exception is raised when pickle.load() is called after all objects have been read?
Answer: EOFError.
Explanation: It indicates that the end of the binary file has been reached.
Q13. Which Python module is used for CSV file handling?
Answer: The csv module.
Q14. Why is newline="" commonly used while opening a CSV file for writing?
Answer: It helps prevent unwanted blank lines between CSV rows, particularly on Windows systems.
Q15. State True or False: writerows() can write multiple rows at once.
Answer: True.
Explanation: writerows() accepts an iterable containing multiple rows.
Q16. Which list method is normally used for the POP operation of a stack?
Answer: pop().
Explanation: list.pop() removes and returns the last element, which represents the top of a stack.
Q17. What is stack underflow?
Answer: Stack underflow occurs when an attempt is made to remove an element from an empty stack.
Q18. What principle does a stack follow?
Answer: A stack follows the LIFO — Last In, First Out principle.
Q19. State True or False: A single try block can have multiple except blocks.
Answer: True.
Explanation: Different except blocks can handle different types of exceptions.
Q20. What is the purpose of the global keyword?
Answer: It allows a function to refer to and modify a variable defined in the global scope.
Section B — Short Answer Questions
Q21. Differentiate between formal and actual parameters with an example.
Answer:
- Formal parameters: Variables written in the function definition.
- Actual parameters: Values supplied during the function call.
def greet(name): # name = formal parameter
print("Hello", name)
greet("Riya") # "Riya" = actual parameter
Q22. Write a valid function header having one compulsory and two default parameters.
Answer:
def calc_total(price, qty=1, discount=0):
Explanation: A non-default parameter must appear before default parameters.
Q23. Differentiate between local and global variables.
| Local Variable | Global Variable |
|---|---|
| Defined inside a function. | Defined outside functions. |
| Normally accessible only within that function. | Can be accessed throughout the program. |
| Exists during function execution. | Normally exists throughout program execution. |
Q24. What is the difference between try and except?
Answer:
trycontains statements that may generate an exception.exceptcontains statements that handle the exception.
try:
x = int(input("Enter number: "))
except ValueError:
print("Invalid input")
Q25. Write a statement to open an existing text file for both reading and writing.
Answer:
f1 = open("data.txt", "r+")
Explanation: r+ allows both reading and writing but requires the file to already exist.
Q26. Differentiate between r+ and w+ file modes.
r+ |
w+ |
|---|---|
| Opens an existing file for reading and writing. | Opens a file for reading and writing. |
| Existing content is preserved. | Existing content is erased. |
| File must already exist. | File is created if it does not exist. |
Q27. Differentiate between read(), readline() and readlines().
| Method | Purpose | Return Type |
|---|---|---|
read() |
Reads the complete file or specified number of characters. | String |
readline() |
Reads one line at a time. | String |
readlines() |
Reads all lines. | List |
Q28. What is the difference between write() and writelines()?
Answer: write() writes a single string, whereas writelines() writes multiple strings supplied through an iterable.
f.write("Hello\n")
f.writelines(["One\n", "Two\n", "Three\n"])
Q29. What is a binary file? Name the module commonly used to store Python objects in binary form.
Answer: A binary file stores data in binary form rather than human-readable characters. The pickle module is commonly used to store and retrieve Python objects.
Q30. Differentiate between writerow() and writerows().
| Method | Purpose |
|---|---|
writerow() |
Writes one row at a time. |
writerows() |
Writes multiple rows at once. |
Section C — Application, Output and Competency-Based Questions
Q31. What will be the output?
def calculate(a, b=5, c=10):
print(a, b, c)
calculate(2, c=3)
Answer:
2 5 3
Explanation: a receives 2, b retains its default value 5, while keyword argument c=3 replaces its default value.
Q32. Find the output.
def test(x):
x = x + 10
return x
a = 5
print(test(a))
print(a)
Answer:
15
5
Explanation: The function works with its parameter x. Changing x does not change the original variable a here.
Q33. Identify the error and correct the following code.
def add(a=10, b):
return a+b
Answer: A non-default argument cannot follow a default argument.
Correct code:
def add(b, a=10):
return a+b
Q34. What will happen when the following program is executed?
try:
n = int(input("Enter number: "))
print(100/n)
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
Answer: The appropriate except block executes depending on the error. A non-numeric input produces Invalid input, while entering 0 produces Cannot divide by zero.
Q35. Write a program to safely read a number from the user and handle invalid input.
Answer:
try:
n = int(input("Enter a number: "))
print("Number =", n)
except ValueError:
print("Please enter a valid integer.")
Explanation: ValueError is generated when the supplied string cannot be converted into an integer.
Q36. A school wants to store student feedback permanently. Which type of file should be selected for simple human-readable text, and which mode should be used to add new feedback without deleting old feedback?
Answer: A text file should be used with a mode.
f = open("feedback.txt", "a")
f.write("Excellent teaching\n")
f.close()
Explanation: Append mode adds new content at the end while preserving existing content.
Q37. Explain why with open() is preferred for file handling.
Answer: The with statement automatically closes the file after the block finishes, even if an exception occurs.
with open("data.txt", "r") as f:
data = f.read()
Explanation: It makes file-handling code safer and reduces the possibility of forgetting close().
Q38. Predict the output.
Stack = []
for i in [12, 25, 8, 40, 15]:
if i % 2 == 0:
Stack.append(i)
while Stack:
print(Stack.pop(), end=" ")
Answer:
40 8 12
Explanation: The even numbers are pushed as 12, 8, 40. Since a stack follows LIFO, they are popped as 40, 8, 12.
Section D — 4 Mark Questions
Q39. Write two functions to analyse a file named Feedback.txt: one to count the number of lines and another to count lines containing the word “good”.
Answer:
def count_lines():
with open("Feedback.txt", "r") as f:
lines = f.readlines()
return len(lines)
def count_positive():
count = 0
with open("Feedback.txt", "r") as f:
for line in f:
if "good" in line.lower():
count += 1
return count
Explanation: The first function counts all lines. The second function traverses the file and counts lines containing the required word without being affected by letter case.
Q40. Write a Python program to create a binary file students.dat and store student records using pickle.
Answer:
import pickle
students = [
[101, "Aman", 88],
[102, "Riya", 94],
[103, "Kabir", 79]
]
with open("students.dat", "wb") as f:
for student in students:
pickle.dump(student, f)
print("Records stored successfully.")
Explanation: Binary writing uses wb. pickle.dump() serializes and stores Python objects in the binary file.
Q41. Write a program to read all records from students.dat created using pickle.
Answer:
import pickle
with open("students.dat", "rb") as f:
try:
while True:
student = pickle.load(f)
print(student)
except EOFError:
pass
Explanation: pickle.load() reads one object at a time. When there are no more objects, EOFError is raised and handled.
Q42. Write a Python program to create a CSV file named marks.csv containing student marks.
Answer:
import csv
data = [
["Roll No", "Name", "Marks"],
[1, "Aman", 88],
[2, "Riya", 94],
[3, "Kabir", 79]
]
with open("marks.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
print("CSV file created.")
Q43. Write a program to read marks.csv using csv.reader() and display every record.
Answer:
import csv
with open("marks.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Explanation: csv.reader() reads the CSV file row by row and returns each row as a list.
Q44. Write a function to implement PUSH and POP operations on a stack using a list.
Answer:
stack = []
def push(item):
stack.append(item)
print("Pushed:", item)
def pop_item():
if len(stack) == 0:
print("Stack Underflow")
else:
print("Popped:", stack.pop())
push(10)
push(20)
push(30)
pop_item()
pop_item()
Explanation: append() inserts an element at the top of the stack, while pop() removes the most recently inserted element.
Q45. A library stores book details in a CSV file. Write a program to count how many books have more than 300 pages.
Answer:
import csv
count = 0
with open("books.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
if int(row["Pages"]) > 300:
count += 1
print("Books with more than 300 pages:", count)
Explanation: DictReader() treats each row as a dictionary, allowing columns to be accessed using their header names.
Q46. Write a program to search for a student record from a binary file using pickle.
Answer:
import pickle
roll = int(input("Enter roll number: "))
found = False
with open("students.dat", "rb") as f:
try:
while True:
student = pickle.load(f)
if student[0] == roll:
print("Record:", student)
found = True
break
except EOFError:
pass
if not found:
print("Record not found.")
Explanation: Each stored object is loaded sequentially and its roll number is compared with the required value.
Section E — HOTS and Case-Based Questions
Q47. Case Study: A school application asks users to enter their age. Sometimes users enter letters instead of numbers. The program should continue running instead of terminating abruptly. Which exception should be handled and why?
Answer: ValueError should be handled because converting a non-numeric string into an integer using int() raises ValueError.
try:
age = int(input("Enter age: "))
except ValueError:
print("Please enter a valid age.")
Q48. Case Study: A school wants to maintain student records that contain lists and dictionaries. It also wants to preserve the Python objects without manually converting them into strings. Which file type and module should be used?
Answer: A binary file with the pickle module should be used.
Explanation: Pickle can serialize Python objects such as lists, dictionaries and tuples and restore them later in their Python form.
Q49. Case Study: A student pushes 10, 20, 30 and 40 into a stack. Then two POP operations are performed. What will be the two popped values and what will remain in the stack?
Answer:
- First POP → 40
- Second POP → 30
- Remaining stack → [10, 20]
Explanation: Stack follows LIFO, so the last inserted item is removed first.
Q50. HOTS: A programmer writes the following code. Identify the problem and suggest a better approach.
f = open("result.txt", "r")
data = f.read()
print(data)
Answer: The file is opened but never explicitly closed.
Better approach:
with open("result.txt", "r") as f:
data = f.read()
print(data)
Explanation: The with statement automatically closes the file after use and is therefore safer and more reliable for file handling.
Quick Revision — Unit 1
| Topic | Remember |
|---|---|
| Functions | def, parameters, arguments, return, scope |
| Exception Handling | try, except, else, finally |
| Text Files | read(), readline(), readlines(), write(), writelines() |
| Binary Files | pickle.dump(), pickle.load(), EOFError |
| CSV Files | csv.reader(), writer(), writerow(), writerows() |
| Stack | LIFO, append(), pop(), Underflow |