TECHNOLOGY • CBSE COMPUTER SCIENCE • CLASSES XI–XII
Python Basics for Class 11 & 12: Important Concepts, Programs and PYQ Practice
Python becomes much easier when you understand what each line does instead of memorising programs. This guide brings together the core concepts, common code patterns and exam-style questions that students should practise for CBSE Computer Science in Classes XI and XII.
Use it for concept revision, output prediction, programming practice and last-minute preparation. Examples are explained step by step, with special attention to common mistakes in school examinations.
1. What CBSE asks you to prepare
Class XI school examinations are set by schools, so the exact annual paper and marks distribution can vary. Class XII board papers follow the published CBSE curriculum and sample-paper pattern. Across the Python portions, students should be comfortable reading code, predicting output, correcting errors and writing a complete function or program from a situation.
| Class / area | High-priority Python topics | Common question formats |
|---|---|---|
| Class XI foundations | Variables, tokens, data types, type conversion, operators, conditions, loops, strings, lists, tuples, dictionaries | MCQs, output prediction, trace a loop, write short programs, find errors |
| Class XII Computer Science (083) | Python revision, functions, scope, text files, CSV files, binary files and stacks | Function-writing questions, file-processing algorithms, stack push/pop, output and error tracing |
| Class XII Informatics Practices (065) | Python as needed for Pandas, Series/DataFrame operations, data visualisation, SQL and data handling | DataFrame/Series operations, plots, SQL queries and application questions |
What “PYQ” means on this page
The worked questions below are original practice questions based on recurring CBSE question patterns, with some tasks adapted in wording and data for learning. They are not presented as verbatim copies of every question from every board-paper set. The stack push/pop practice reflects the type of stack-function question found in the official CBSE Class XII Computer Science 2025 paper; use the linked original paper for exact wording. Class XI papers are generally school-set rather than one common nationwide CBSE board paper. For authentic paper wording, use the official CBSE sample papers, marking schemes and previous-year question-paper archive linked at the end.
2. Python fundamentals
2.1 A first program, comments and indentation
print("Hello, Python!")
# This is a comment
marks = 87
print("Marks =", marks)print() displays output. A comment begins with # and is ignored by the interpreter. Indentation (spaces at the beginning of a line) defines a block in statements such as if, for, while and def. Use consistent indentation—normally four spaces.
2.2 Tokens, identifiers and keywords
- Keywords: reserved words such as
if,else,for,while,def,return,TrueandNone. - Identifiers: names for variables and functions. They may contain letters, digits and underscores, but cannot begin with a digit. Python is case-sensitive.
- Literals: fixed values such as
25,3.5,"CBSE"andTrue. - Operators: symbols/words that perform operations, such as
+,//andin. - Punctuators: symbols such as parentheses, commas, colons and brackets.
total_marks is a valid identifier; 2marks is not. score and Score are different names.2.3 Core data types
| Type | Example | Important point |
|---|---|---|
int | 12 | Whole number |
float | 12.5 | Number with a fractional part |
complex | 2+3j | Complex number; j denotes the imaginary part |
bool | True, False | Logical values; capitalisation matters |
str | "Saraswat" | Text; immutable sequence |
list | [10, 20, 30] | Ordered and mutable |
tuple | (10, 20, 30) | Ordered and immutable |
dict | {"A": 90} | Stores key–value pairs; mutable |
NoneType | None | Represents the absence of a value |
2.4 Input and type conversion
input() returns text (a string), even if the user types digits. Convert the value when arithmetic is required.
name = input("Enter name: ")
age = int(input("Enter age: "))
percentage = float(input("Enter percentage: "))
print(name, age, percentage)Examples of explicit conversion: int("25") gives 25; float("4.5") gives 4.5; str(18) gives "18". Converting "4.5" directly to int raises a ValueError.
3. Operators and expressions
| Operator group | Operators | Example / meaning |
|---|---|---|
| Arithmetic | + - * / // % ** | 17 // 5 is 3; 17 % 5 is 2 |
| Comparison | == != > < >= <= | Produce True or False |
| Logical | and or not | Combine or reverse conditions |
| Assignment | = += -= *= etc. | x += 2 means x = x + 2 |
| Membership | in, not in | 3 in [1,3,5] is True |
| Identity | is, is not | Tests object identity, not general value equality |
3.1 Division: a frequent output question
print(17 / 5)
print(17 // 5)
print(17 % 5)
print(2 ** 3 ** 2)3.4
3
2
512
/ performs true division; // gives floor division; % gives the remainder. Exponentiation associates from right to left, so 2 ** 3 ** 2 means 2 ** (3 ** 2).
3.2 Trace the expression carefully
a = 7 + 3 * 2 ** 2
print(a)19
Exponentiation is evaluated first: 2 ** 2 = 4; then multiplication: 3 * 4 = 12; then addition: 7 + 12 = 19. Parentheses can make the intended order clearer.
== compares values; = assigns a value. Use == inside a condition when testing equality.3A. Python modules: math, random and statistics
The current Class XI Computer Science syllabus lists the math, random and statistics modules. Import a module before using its functions, or import selected functions directly.
import math
import random
import statistics
print(math.sqrt(81))
print(math.ceil(4.2))
print(math.floor(4.8))
print(random.randint(1, 6))
print(statistics.mean([10, 20, 30]))The random result can vary each time the program runs. randint(1, 6) can return either endpoint, including 1 and 6. Other syllabus-listed examples include math.pi, math.e, math.pow(), random.randrange(), statistics.median() and statistics.mode().
from math import sqrt, ceil
print(sqrt(49))
print(ceil(3.1))4. Conditional statements and loops
4.1 if, if–else and if–elif–else
marks = 76
if marks >= 90:
grade = "A1"
elif marks >= 75:
grade = "A2"
elif marks >= 60:
grade = "B"
else:
grade = "C"
print(grade)A2
Conditions are checked from top to bottom. The first true branch runs; later branches are skipped. A colon and an indented block are required.
4.2 for loop and range()
for i in range(2, 8, 2):
print(i, end=" ")2 4 6
range(start, stop, step) includes the start (when reached) but excludes the stop. Therefore, range(2, 8, 2) produces 2, 4 and 6.
4.3 while loop, break and continue
n = 1
while n <= 5:
if n == 3:
n += 1
continue
print(n, end=" ")
n += 11 2 4 5
continue skips the remaining statements in the current iteration. break exits the loop. In a while loop, update the control variable so that the loop can finish.
4.4 Classic programming questions
Find the factorial of a number
n = int(input("Enter a non-negative integer: "))
fact = 1
for i in range(1, n + 1):
fact *= i
print("Factorial =", fact)For n = 5, the result is 120. The initial value must be 1 because multiplying by 0 would make the result 0.
Check whether a number is prime
n = int(input("Enter an integer: "))
if n < 2:
print("Not prime")
else:
is_prime = True
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
is_prime = False
break
print("Prime" if is_prime else "Not prime")A prime number is greater than 1 and has no positive divisors other than 1 and itself.
Sum the digits of a positive integer
n = int(input("Enter a positive integer: "))
total = 0
while n > 0:
total += n % 10
n //= 10
print(total)For input 482, output is 14. n % 10 extracts the last digit and n // 10 removes it.
5. Strings: indexing, slicing and methods
A string is an immutable sequence of characters. Indexing starts at 0 from the left and at −1 from the right. A slice follows text[start:stop:step]; the stop index is excluded.
s = "COMPUTER"
print(s[0], s[-1])
print(s[1:5])
print(s[::-1])
print("put" in s.lower())C R
OMPU
RETUPMOC
True
The final line converts the string to lowercase before checking membership.
5.1 Useful string methods
| Method / function | Purpose | Example |
|---|---|---|
len(s) | Number of characters | len("CBSE") → 4 |
lower(), upper(), title() | Change letter case | "hello".upper() → "HELLO" |
count(sub) | Count occurrences | "banana".count("a") → 3 |
find(sub) | Index of first occurrence, or −1 | "banana".find("na") → 2 |
index(sub) | Index of first occurrence; error if absent | "cat".index("a") → 1 |
replace(old,new) | Return a modified string | "a-b".replace("-"," ") → "a b" |
split() | Split into a list of words/parts | "a b c".split() → ['a','b','c'] |
strip() | Remove whitespace at both ends | " hi ".strip() → "hi" |
startswith(), endswith() | Test beginning or ending | "python.py".endswith(".py") → True |
isalpha(), isdigit(), isalnum() | Character tests | "123".isdigit() → True |
partition(sep) | Return a 3-part tuple | "a b".partition(" ") → ('a',' ','b') |
5.2 Exam-style output: partition()
print("Amrit Mahotsav @ 75".partition(" "))('Amrit', ' ', 'Mahotsav @ 75')
partition() splits at the first occurrence of the separator and returns a tuple containing the part before it, the separator itself and the part after it. If the separator is absent, the original string is the first item and the other two items are empty strings.
s[0] = "X" causes a TypeError. Methods such as replace() return a new string; assign it if you want to keep the result.6. Lists
A list is an ordered, mutable collection. It can contain mixed data types and nested lists. Lists are widely used in Class XI questions and to implement a stack in Class XII.
marks = [72, 88, 65, 91]
marks.append(79)
marks.insert(1, 80)
marks.remove(65)
print(marks)
print(marks[1:4])
print(sum(marks), max(marks), min(marks))[72, 80, 88, 91, 79]
[80, 88, 91]
410 91 72
6.1 List methods you should know
| Method / function | What it does | Exam caution |
|---|---|---|
append(x) | Adds one item at the end | a.append([4,5]) adds a nested list as one item |
extend(items) | Adds each item from an iterable | a.extend([4,5]) adds two items |
insert(i,x) | Inserts at index i | Existing items shift right |
remove(x) | Removes the first matching value | Raises an error if the value is absent |
pop(), pop(i) | Removes and returns last item or item at index | Raises an error on an empty list |
sort() | Sorts the list in place | Returns None |
sorted(a) | Returns a new sorted list | Original list stays unchanged |
reverse() | Reverses list in place | Returns None |
count(x), index(x) | Count / find first index | index() errors if absent |
len(), sum(), min(), max() | Useful built-in functions | Values must be compatible for comparison/summation |
6.2 append() versus extend()
a = [1, 2]
a.append([3, 4])
print(a)
b = [1, 2]
b.extend([3, 4])
print(b)[1, 2, [3, 4]]
[1, 2, 3, 4]
6.3 Linear search and frequency count
numbers = [4, 7, 2, 7, 9]
target = 7
if target in numbers:
print("Found at index", numbers.index(target))
else:
print("Not found")
print("Frequency =", numbers.count(target))Found at index 1
Frequency = 2
For a question that asks you to write linear search yourself, use a loop and compare each element with the target rather than relying on index().
numbers = [4, 7, 2, 7, 9]
target = int(input("Search for: "))
position = -1
for i in range(len(numbers)):
if numbers[i] == target:
position = i
break
if position == -1:
print("Not found")
else:
print("Found at index", position)6.4 A subtle mutability question
a = [10, 20, 30]
b = a
b[0] = 99
print(a)[99, 20, 30]
b = a does not make a separate list; both names refer to the same list. Use b = a.copy() or b = a[:] for a shallow copy.
7. Tuples
A tuple is an ordered, immutable sequence. It supports indexing, slicing, membership, iteration and methods such as count() and index().
t = (10, 20, 10, 40)
print(t[1])
print(t.count(10))
print(t.index(40))
print(t[1:3])
single = (5,)
print(type(single))20
2
3
(20, 10)
<class 'tuple'>
The comma creates a single-item tuple: (5,). (5) is simply the integer 5 inside parentheses.
Nested list and tuple: a classic misconception
a = [1, 2, (3, 4)]
a[2][1] = 5This raises a TypeError. The outer list is mutable, but the item at index 2 is a tuple, and tuple elements cannot be reassigned. A list containing a tuple does not make the tuple itself mutable.
8. Dictionaries
A dictionary stores key–value pairs. Keys must be hashable and unique; assigning a value to an existing key updates that value. Dictionaries are mutable.
marks = {"Aarav": 88, "Diya": 94}
marks["Kabir"] = 81
marks["Aarav"] = 90
print(marks["Diya"])
print(marks.get("Riya", "Not found"))
print(list(marks.keys()))
print(list(marks.values()))
print(list(marks.items()))94
Not found
['Aarav', 'Diya', 'Kabir']
[90, 94, 81]
[('Aarav', 90), ('Diya', 94), ('Kabir', 81)]
8.1 Important dictionary methods
| Method / statement | Purpose |
|---|---|
keys(), values(), items() | View keys, values or key–value pairs |
get(key, default) | Read a value safely; return the default if absent |
update(other) | Add or update entries |
pop(key) | Remove a key and return its value |
popitem() | Remove and return the most recently inserted pair in modern Python |
clear() | Remove all entries |
del d[key] | Delete a specified key |
setdefault(key, default) | Return the value; insert the default if the key is missing |
len(d), sorted(d) | Count entries / return sorted keys |
8.2 Count each character using a dictionary
This is a useful long-answer pattern because it combines a loop, a condition and dictionary updates.
text = "banana"
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq){'b': 1, 'a': 3, 'n': 2}
Shorter equivalent: freq[ch] = freq.get(ch, 0) + 1 inside the loop. If a question asks for a case-insensitive count, process text.lower() first.
8.3 Traverse a dictionary
salary = {"Aman": 25000, "Riya": 30000}
for name, amount in salary.items():
print(name, amount)Use for key in d to iterate over keys or for key, value in d.items() to access both components.
9. Functions: parameters, return values and scope
A function is a named, reusable block of code. Define it with def. Parameters receive inputs; return sends a result back to the caller. print() displays a value but does not return it as the function's result.
def area_rectangle(length, breadth):
return length * breadth
answer = area_rectangle(8, 5)
print(answer)40
9.1 print() versus return
def first():
print(5)
def second():
return 5
x = first()
y = second()
print(x, y)5
None 5
The first function displays 5 and then implicitly returns None. The second returns 5 to the caller.
9.2 Default and positional arguments
def greet(name, message="Welcome"):
print(message, name)
greet("Asha")
greet("Asha", "Good morning")Welcome Asha
Good morning Asha
9.3 Local and global variables
x = 10
def show():
x = 4
print(x)
show()
print(x)4
10
The assignment inside show() creates a local variable. It does not change the global x. Avoid using global unless the question specifically requires it.
9.4 A function to return the largest of three numbers
def largest(a, b, c):
if a >= b and a >= c:
return a
elif b >= a and b >= c:
return b
else:
return c
print(largest(12, 27, 19))27
9.5 Recursion: understand the base case
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(4))24
Each recursive call reduces the problem. The base case stops the calls. Whether recursion is part of your examinable syllabus depends on the prescribed course/session; learn it if your teacher or syllabus includes it.
10. Text file handling (Class XII Computer Science)
File questions often give a scenario and ask you to count, display, search or process words, lines or characters. Learn the difference between reading the whole file, reading one line and traversing line by line.
| Mode | Meaning | Important point |
|---|---|---|
"r" | Read | File must exist |
"w" | Write | Creates a file or overwrites its existing contents |
"a" | Append | Adds content at the end |
"rb", "wb" | Read/write binary | Used with binary data and pickled objects |
Prefer with open(...): it closes the file automatically when the block ends.
10.1 Read and display a file
with open("Notes.txt", "r", encoding="utf-8") as f:
data = f.read()
print(data)Common reading methods:
read()reads the remaining content as one string.readline()reads one line.readlines()returns a list of lines.for line in f:processes the file one line at a time.
10.1A File pointer: seek() and tell()
tell() returns the current position of the file pointer. seek(position) moves the pointer to a specified position.
with open("Notes.txt", "r", encoding="utf-8") as f:
print(f.tell())
first = f.read(5)
print(first)
print(f.tell())
f.seek(0)
print(f.readline())The initial pointer position is normally 0. After reading, the position advances; seek(0) returns it to the beginning.
10.2 Count words in a text file
def count_words():
with open("Notes.txt", "r", encoding="utf-8") as f:
text = f.read()
words = text.split()
print("Word count =", len(words))
count_words()split() without an argument separates on runs of whitespace, so it handles multiple spaces and line breaks better than splitting on one literal space.
10.3 Count lines that contain a particular word
def count_python_lines():
count = 0
with open("Prog.txt", "r", encoding="utf-8") as f:
for line in f:
if "python" in line.lower():
count += 1
print("Matching lines =", count)This counts matching lines, not every occurrence of the word. To count occurrences, split into words or use a suitable counting method and state how punctuation is handled.
10.4 Count vowels, uppercase letters and words
def analyse_file():
vowels = 0
uppercase = 0
words = 0
with open("Story.txt", "r", encoding="utf-8") as f:
for line in f:
words += len(line.split())
for ch in line:
if ch.lower() in "aeiou":
vowels += 1
if ch.isupper():
uppercase += 1
print("Vowels:", vowels)
print("Uppercase:", uppercase)
print("Words:", words)Keep the counter initialisation outside the loop. If the task asks for words beginning with a particular letter, inspect each word after split().
10.5 Write to a file
with open("Result.txt", "w", encoding="utf-8") as f:
f.write("Python is useful.\n")
f.write("Practise every day.\n")write() does not add a newline automatically. Include \n where a line break is needed. writelines() writes each string from an iterable, but it does not insert newline characters automatically.
"w" destroys its previous contents. Use it only when overwriting is intended. For practical work, make sure the named input file actually exists in the working directory.11. CSV and binary file basics (Class XII Computer Science)
11.1 CSV files
CSV (comma-separated values) stores tabular records as text. Python's csv module handles quoted values and commas more reliably than manually splitting every line.
import csv
with open("students.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["RollNo", "Name", "Marks"])
writer.writerow([1, "Aarav", 88])
writer.writerow([2, "Diya", 94])import csv
with open("students.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)Rows read by csv.reader are lists of strings. Convert numeric fields with int() or float() before calculations. If the syllabus specifically teaches csv.writer and csv.reader, practise their exact syntax.
11.2 Exception handling: try, except and finally
The current Class XII Computer Science syllabus includes handling exceptions. A try block contains code that may fail; except handles a specified error; finally runs whether an exception occurs or not.
try:
number = int(input("Enter a number: "))
print(100 / number)
except ValueError:
print("Please enter an integer.")
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Program finished.")Use specific exceptions where possible. Avoid a broad except: unless the question explicitly calls for it.
11.3 File modes at a glance
| Mode | Meaning |
|---|---|
r+ | Read and write an existing file; pointer begins at the start. |
w+ | Read and write; creates or truncates the file. |
a+ | Read and append; writes go to the end. |
rb+, wb+, ab+ | Binary equivalents for read/write, write/read and append/read operations. |
11.4 Binary files and pickle
In CBSE Computer Science, binary-file programs commonly use the pickle module to write and retrieve Python records. The key operations are pickle.dump() to write and pickle.load() to read.
import pickle
record = [101, "Meera", 91]
with open("student.dat", "wb") as f:
pickle.dump(record, f)import pickle
try:
with open("student.dat", "rb") as f:
while True:
record = pickle.load(f)
print(record)
except EOFError:
passEOFError signals that no more pickled objects remain. In a question requiring search or update, read each record, test the specified field and display or write the matching record as requested. When rewriting a binary file, take care not to lose records that do not match the update condition.
Binary-file search pattern
import pickle
def search_student(roll_to_find):
found = False
try:
with open("student.dat", "rb") as f:
while True:
rec = pickle.load(f)
if rec[0] == roll_to_find:
print(rec)
found = True
except EOFError:
pass
if not found:
print("Record not found")This assumes each stored record is a list whose first element is the roll number. Match the record structure given in the examination question.
12. Stack using a Python list
A stack follows LIFO—Last In, First Out. The most recently pushed item is the first one popped. A Python list is commonly used to implement a stack.
- Push: insert an item at the top, usually with
append(). - Pop: remove and return the top item, usually with
pop(). - Underflow: attempt to pop from an empty stack.
- Display/peek: inspect items or the top without deleting them, according to the question.
stack = []
stack.append("Red")
stack.append("Blue")
stack.append("Green")
print(stack)
print("Popped:", stack.pop())
print(stack)['Red', 'Blue', 'Green']
Popped: Green
['Red', 'Blue']
12.1 Exam-ready push, pop and display functions
def push_item(stack, item):
stack.append(item)
def pop_item(stack):
if len(stack) == 0:
print("Stack Underflow")
return None
return stack.pop()
def display_stack(stack):
if len(stack) == 0:
print("Empty Stack")
else:
for item in reversed(stack):
print(item)Use the exact function names and empty-stack messages stated in the question. If the task says display all items without deleting them, do not call pop() during display.
12.2 Push the last five elements of a list
def push_trail(N, myStack):
for item in N[-5:]:
myStack.append(item)
N = [1, 2, 3, 4, 5, 6, 7]
myStack = []
push_trail(N, myStack)
print(myStack)[3, 4, 5, 6, 7]
N[-5:] selects the last five elements in their original order. This is a concise solution when the question guarantees that the list contains at least five elements.
13. Common errors and how to avoid them
| Error / issue | Typical cause | Correction |
|---|---|---|
SyntaxError | Missing colon, unmatched bracket or invalid syntax | Check punctuation and statement structure |
NameError | Using a variable/function name that is not defined | Check spelling and scope |
TypeError | Unsupported operation for the given types | Convert compatible types or correct the operation |
ValueError | Valid function, unsuitable value such as int("abc") | Validate the input before conversion |
IndexError | List/string index is outside its valid range | Check length and indexing |
KeyError | Accessing a missing dictionary key with square brackets | Use get() when a missing key is expected |
IndentationError | Inconsistent or missing indentation | Indent blocks consistently |
| Infinite loop | Loop condition never becomes false | Update the control variable or use a correct exit condition |
Find the mistake
for i in range(1, 5)
print(i)Correction: place a colon after range(1, 5).
age = input("Age: ")
print(age + 1)Correction: use age = int(input("Age: ")) if an integer age is intended.
14. Solved CBSE PYQ-style practice set
These questions mirror the formats that appear in school and board-style Computer Science papers: MCQs, output prediction, short code tracing, function-writing, file handling and stack operations. They are rewritten practice items, not a claim that each line appeared verbatim in an official paper.
Q1. Predict the output.
x = 7 * 8 / 5 // 2
print(x)Show solution
Answer: 5.0
7 * 8 = 56; 56 / 5 = 11.2; then 11.2 // 2 = 5.0 because floor division on a float produces a float result.
Q2. Which is an invalid Python identifier?
(a) CS_345 (b) _345 (c) 345_ (d) CS345
Show solution
Answer: (c) 345_. An identifier cannot begin with a digit.
Q3. What does this print?
s = "This is Computer Science"
print(s.find("i"))Show solution
Answer: 2. The first i is at index 2 because indexing begins at zero. find() returns −1 when the substring is not found.
Q4. Predict the output.
a = [2, 4, 6]
print(a.append(8))
print(a)Show solution
Answer:None[2, 4, 6, 8]
append() changes the original list and returns None.
Q5. Find the output.
total = 0
for i in range(1, 6):
if i % 2 == 0:
total += i
print(total)Show solution
Answer: 6. The even values are 2 and 4, so the total is 2 + 4 = 6.
Q6. What is the result?
word = "Mississippi"
print(word.count("ss"))
print(word.replace("ss", "X"))Show solution
Answer:2MiXiXippi
The non-overlapping substring "ss" occurs twice. replace() replaces each matching occurrence.
Q7. Predict the output.
d = {"A": 2, "B": 3}
d["A"] = d["A"] + 4
d["C"] = 5
print(len(d), d["A"])Show solution
Answer: 3 6. The value for A changes to 6, and C is added as a new key. There are three keys.
Q8. Write a function to count the vowels in a string.
Show solution
def count_vowels(text):
count = 0
for ch in text.lower():
if ch in "aeiou":
count += 1
return count
print(count_vowels("Computer Science"))Output: 6. The function returns the count, so the caller can display or reuse it.
Q9. Write a program to find the maximum, minimum and average of numbers in a list.
Show solution
numbers = [12, 18, 9, 21, 15]
if len(numbers) > 0:
print("Maximum =", max(numbers))
print("Minimum =", min(numbers))
print("Average =", sum(numbers) / len(numbers))
else:
print("List is empty")Output: Maximum = 21; Minimum = 9; Average = 15.0.
Q10. Write a function that accepts a list and returns a new list containing only even numbers.
Show solution
def even_numbers(values):
result = []
for value in values:
if value % 2 == 0:
result.append(value)
return result
print(even_numbers([3, 8, 11, 14, 20]))Output: [8, 14, 20].
Q11. Write a function to count how many times the word “python” occurs in a text file, ignoring case.
Show solution
def count_python():
count = 0
with open("Prog.txt", "r", encoding="utf-8") as f:
words = f.read().lower().split()
for word in words:
word = word.strip(".,!?;:()[]{}\"'")
if word == "python":
count += 1
print("Python occurs", count, "times.")This solution ignores case and removes common punctuation around a word. If your textbook or question defines a simpler counting rule, follow that rule exactly.
Q12. Write a pop function that returns the top item, or displays “Stack Underflow” and returns None when empty.
Show solution
def pop_one(myStack):
if len(myStack) == 0:
print("Stack Underflow")
return None
return myStack.pop()The empty check must occur before calling pop().
Q13. Create a dictionary that records the frequency of each character in an input string.
Show solution
value = input("Enter a string: ")
D = {}
for ch in value:
if ch in D:
D[ch] += 1
else:
D[ch] = 1
print(D)For input Mussoorie, the frequency dictionary records each distinct character and its number of appearances. The code is case-sensitive, so uppercase and lowercase letters are separate keys.
Q14. Read a CSV file and display records whose marks are at least 80.
Show solution
import csv
with open("students.csv", "r", newline="", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader, None)
for row in reader:
if row and float(row[2]) >= 80:
print(row)This assumes the first row is a header and marks are stored in the third column. Adapt the index to the record structure in the question.
Q15. A binary file stores records as [roll number, name, marks]. Display the records with marks above 90.
Show solution
import pickle
def display_above_90():
try:
with open("student.dat", "rb") as f:
while True:
rec = pickle.load(f)
if rec[2] > 90:
print(rec)
except EOFError:
passIndex 2 refers to marks in the assumed record format. Handle end-of-file with EOFError as shown.
Q16. Explain why this code fails.
t = (1, 2, 3)
t[0] = 9Show solution
It raises TypeError because tuples are immutable. To change an element, create a new tuple or use a list if modification is required.
15. Last-minute revision checklist
- Know the difference between
/,//,%and**. - Practise string slicing, negative indexing,
find(),count(),split()andpartition(). - Know which list methods mutate the list and which built-in functions return a new result.
- Remember: strings and tuples are immutable; lists and dictionaries are mutable.
- Trace nested loops and
range()boundaries without skipping iterations. - Write functions with correct parameters, indentation and a suitable
return. - For text files, distinguish
read(),readline(),readlines()and line-by-line processing. - For CSV, use
csv.reader/csv.writerand convert numeric strings before arithmetic. - For binary files, know
pickle.dump(),pickle.load(),wb,rbandEOFError. - For stacks, remember LIFO, push with
append(), pop withpop(), and check for underflow. - Read the question carefully: preserve the requested function name, filename, field order and exact message.
- Practise official sample papers and marking schemes under timed conditions.
16. Official CBSE resources and further practice
Use the official resources below to confirm the topics for your academic session and to practise with authentic question papers and marking schemes.
- CBSE Curriculum 2026–27 — check the current Class XI/XII Computer Science or Informatics Practices syllabus for your subject.
- Official Computer Science syllabus PDF (2026–27) — includes Class XI Python and Class XII functions, exception handling, file handling and stacks.
- CBSE Class XII Sample Question Papers and Marking Schemes 2026–27 — check this page for the current session’s official sample materials.
- CBSE Class XII Sample Papers and Marking Schemes 2025–26 — useful for additional practice with the previous session’s sample paper.
- Official CBSE Class XII Computer Science board paper (2025, Code 91) — includes Python stack and function-writing questions.
- CBSE Previous-Year Question Papers — official question-paper archive; select the examination year and subject.
- CBSE Marking Schemes — use these to understand expected answer structure and mark allocation.
- CBSE Computer Science Learning Framework — supporting learning outcomes for topics such as file handling and stacks.
Frequently asked questions
Is this page enough for the complete CBSE Class 11 and 12 Computer Science syllabus?
This is a Python-focused revision guide, not the entire Computer Science syllabus. You must also study the other prescribed units, such as computer systems and networks in Class XI, and SQL/database concepts and networking in Class XII, as applicable to your course and session.
Are all questions on this page exact previous-year CBSE questions?
No. The solved set is clearly labelled PYQ-style practice and uses common exam formats and recurring concepts. Follow the official CBSE paper links for exact paper sets and wording.
Should Class 12 students study Pandas from this page?
Students taking Informatics Practices should also study the prescribed Pandas and data-visualisation topics. This page is primarily centred on the Python topics commonly taught in Computer Science (083), with a note about the different IP syllabus.
Which Python topics should I practise first?
Begin with data types, operators, conditions, loops, strings and lists. Then practise dictionaries and functions. For Class XII Computer Science, give dedicated practice time to text/CSV/binary file handling and stack programs.