Unit 1: Competency-Based Questions
In accordance with the latest CBSE guidelines, a significant portion of your exam will consist of competency-based questions. These questions test your ability to apply the concepts of Python programming to real-world scenarios, debug code, and understand the logic behind algorithms.
This section provides a set of questions modeled on the previous 5 years of CBSE Question Papers and Official Sample Papers.
1. Output Based Questions (Tracing and Logic)
Question 1.1 What will be the output of the following Python code snippet? Explain the logic.
def changeList(L, n):
for i in range(len(L)):
if L[i] % n == 0:
L[i] = L[i] // n
else:
L[i] = L[i] * n
return L
myList = [10, 20, 30, 40, 50]
print(changeList(myList, 10))
Expected Answer:
[1, 2, 3, 4, 5]
Logic: The loop iterates through each element. Since every element in myList is divisible by n (which is 10), the if condition is always true. Thus, each element is replaced by its integer division by 10. List is mutable, so changes persist.
Question 1.2 Find and write the output of the following python code:
x = "Global"
def func1():
x = "Enclosing"
def func2():
global x
x = "Local"
func2()
print("Inner:", x)
func1()
print("Outer:", x)
Expected Answer:
Inner: Enclosing
Outer: Local
Logic:
func1()starts. A local variablex(“Enclosing”) is created.func2()is called. Insidefunc2(), theglobal xstatement binds the local namexto the global variable. It then sets the globalxto “Local”.- Inside
func1(),print("Inner:", x)prints the localxbelonging tofunc1, which is still “Enclosing”. - Finally, the main program prints the global
x, which was modified byfunc2()to “Local”.
2. Debugging and Error Spotting
Question 2.1 Raman has written the following code to find the sum of all digit characters in a string. However, his code has some errors. Rewrite the correct code and underline the corrections made.
def sumDigits(s)
sum == 0
for char in s:
if char.isdigit():
sum = sum + char
Print("Sum is", sum)
sumDigits("Abc12d3")
Corrected Code:
def sumDigits(s): # Correction: Added colon ':'
sum = 0 # Correction: Assignment operator '=' instead of '=='
for char in s:
if char.isdigit():
sum = sum + int(char) # Correction: Converted string character to int
print("Sum is", sum) # Correction: 'print' must be all lowercase
sumDigits("Abc12d3")
3. Advanced File Handling Scenarios
Question 3.1 (Text Files)
A text file named "STORY.txt" contains some text. Write a user-defined function count_words() in Python that counts and displays the number of words in the file that start with an uppercase vowel (A, E, I, O, U).
Solution Idea:
def count_words():
count = 0
vowels = ['A', 'E', 'I', 'O', 'U']
try:
with open("STORY.txt", "r") as file:
data = file.read()
words = data.split() # Splits text into a list of words
for word in words:
if word[0] in vowels: # Checks if the first letter is an uppercase vowel
count += 1
print("Total words starting with uppercase vowel:", count)
except FileNotFoundError:
print("File not found.")
Question 3.2 (Binary Files - Case Study Based)
A binary file "book.dat" has structure [BookNo, Book_Name, Author, Price].
Write a function Search_Author(Author_Name) in Python that searches and displays the details of all books written by the author whose name is passed as an argument. Assume the module pickle is already imported.
Solution Idea:
import pickle
def Search_Author(Author_Name):
found = False
try:
with open("book.dat", "rb") as file:
while True:
try:
book_record = pickle.load(file)
# Check if the 3rd element (index 2) matches the Author_Name
if book_record[2] == Author_Name:
print(book_record)
found = True
except EOFError:
break # Reached the End of File
if not found:
print(f"No books found by author {Author_Name}")
except FileNotFoundError:
print("File 'book.dat' not found.")
4. Stack Implementation (Application Based)
Question 4.1
A list Names contains names of students. Write a program to implement a stack allowing Push and Pop operations for the students whose name starts with the alphabet ‘A’.
For example: If Names = ["Amit", "Rohit", "Akash", "Suman"], the stack should store “Amit” and “Akash”.
Solution Idea:
Names = ["Amit", "Rohit", "Akash", "Suman"]
stack_A = []
def Push_A(names_list, stk):
for name in names_list:
if name[0].upper() == 'A':
stk.append(name)
print(f"Pushed: {name}")
def Pop_A(stk):
if len(stk) == 0:
print("Underflow")
else:
removed = stk.pop()
print(f"Popped: {removed}")
# Execution
Push_A(Names, stack_A)
Pop_A(stack_A)
Pop_A(stack_A)
Pop_A(stack_A) # Tests underflow
Study Tip
Practicing these types of questions regularly is the key to scoring well. Focus heavily on identifying what kind of data structure or file operation is best suited for the scenario presented in the exam.