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.

First, check your subject: this guide mainly follows the Python topics used in CBSE Computer Science (083). Class XI introduces programming fundamentals and collections. Class XII Computer Science revisits Python and emphasises functions, text/CSV/binary file handling and stacks, alongside SQL and networking. Informatics Practices (065) has a different emphasis in Class XII, including Pandas, data visualisation and SQL. Always match your preparation with the syllabus for your own subject and academic session.

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 / areaHigh-priority Python topicsCommon question formats
Class XI foundationsVariables, tokens, data types, type conversion, operators, conditions, loops, strings, lists, tuples, dictionariesMCQs, 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 stacksFunction-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 handlingDataFrame/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.

Exam habit: In output questions, trace values line by line. In programming questions, use the function name and parameters exactly as given, respect indentation, handle empty files/stacks where required, and show the requested output or return value.

2. Python fundamentals

2.1 A first program, comments and indentation

PYTHON
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, True and None.
  • 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" and True.
  • Operators: symbols/words that perform operations, such as +, // and in.
  • Punctuators: symbols such as parentheses, commas, colons and brackets.
Quick check: total_marks is a valid identifier; 2marks is not. score and Score are different names.

2.3 Core data types

TypeExampleImportant point
int12Whole number
float12.5Number with a fractional part
complex2+3jComplex number; j denotes the imaginary part
boolTrue, FalseLogical 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
NoneTypeNoneRepresents 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.

PYTHON
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 groupOperatorsExample / meaning
Arithmetic+ - * / // % **17 // 5 is 3; 17 % 5 is 2
Comparison== != > < >= <=Produce True or False
Logicaland or notCombine or reverse conditions
Assignment= += -= *= etc.x += 2 means x = x + 2
Membershipin, not in3 in [1,3,5] is True
Identityis, is notTests object identity, not general value equality

3.1 Division: a frequent output question

PYTHON
print(17 / 5)
print(17 // 5)
print(17 % 5)
print(2 ** 3 ** 2)
Output
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

PYTHON
a = 7 + 3 * 2 ** 2
print(a)
Output
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.

Common trap: == 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.

PYTHON
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().

ALTERNATIVE IMPORT STYLE
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

PYTHON
marks = 76
if marks >= 90:
    grade = "A1"
elif marks >= 75:
    grade = "A2"
elif marks >= 60:
    grade = "B"
else:
    grade = "C"
print(grade)
Output
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()

PYTHON
for i in range(2, 8, 2):
    print(i, end=" ")
Output
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

PYTHON
n = 1
while n <= 5:
    if n == 3:
        n += 1
        continue
    print(n, end=" ")
    n += 1
Output
1 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

PYTHON
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

PYTHON
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

PYTHON
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.

PYTHON
s = "COMPUTER"
print(s[0], s[-1])
print(s[1:5])
print(s[::-1])
print("put" in s.lower())
Output
C R
OMPU
RETUPMOC
True

The final line converts the string to lowercase before checking membership.

5.1 Useful string methods

Method / functionPurposeExample
len(s)Number of characterslen("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()

PYTHON
print("Amrit Mahotsav @ 75".partition(" "))
Output
('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.

Remember: strings are immutable. A statement such as 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.

PYTHON
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))
Output
[72, 80, 88, 91, 79]
[80, 88, 91]
410 91 72

6.1 List methods you should know

Method / functionWhat it doesExam caution
append(x)Adds one item at the enda.append([4,5]) adds a nested list as one item
extend(items)Adds each item from an iterablea.extend([4,5]) adds two items
insert(i,x)Inserts at index iExisting items shift right
remove(x)Removes the first matching valueRaises an error if the value is absent
pop(), pop(i)Removes and returns last item or item at indexRaises an error on an empty list
sort()Sorts the list in placeReturns None
sorted(a)Returns a new sorted listOriginal list stays unchanged
reverse()Reverses list in placeReturns None
count(x), index(x)Count / find first indexindex() errors if absent
len(), sum(), min(), max()Useful built-in functionsValues must be compatible for comparison/summation

6.2 append() versus extend()

PYTHON
a = [1, 2]
a.append([3, 4])
print(a)

b = [1, 2]
b.extend([3, 4])
print(b)
Output
[1, 2, [3, 4]]
[1, 2, 3, 4]

6.3 Linear search and frequency count

PYTHON
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))
Output
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().

PYTHON — LINEAR SEARCH
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

PYTHON
a = [10, 20, 30]
b = a
b[0] = 99
print(a)
Output
[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().

PYTHON
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))
Output
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

PYTHON
a = [1, 2, (3, 4)]
a[2][1] = 5

This 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.

PYTHON
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()))
Output
94
Not found
['Aarav', 'Diya', 'Kabir']
[90, 94, 81]
[('Aarav', 90), ('Diya', 94), ('Kabir', 81)]

8.1 Important dictionary methods

Method / statementPurpose
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.

PYTHON
text = "banana"
freq = {}
for ch in text:
    if ch in freq:
        freq[ch] += 1
    else:
        freq[ch] = 1
print(freq)
Output
{'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

PYTHON
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.

PYTHON
def area_rectangle(length, breadth):
    return length * breadth

answer = area_rectangle(8, 5)
print(answer)
Output
40

9.1 print() versus return

PYTHON
def first():
    print(5)

def second():
    return 5

x = first()
y = second()
print(x, y)
Output
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

PYTHON
def greet(name, message="Welcome"):
    print(message, name)

greet("Asha")
greet("Asha", "Good morning")
Output
Welcome Asha
Good morning Asha

9.3 Local and global variables

PYTHON
x = 10

def show():
    x = 4
    print(x)

show()
print(x)
Output
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

PYTHON
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))
Output
27

9.5 Recursion: understand the base case

PYTHON
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

print(factorial(4))
Output
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.

ModeMeaningImportant point
"r"ReadFile must exist
"w"WriteCreates a file or overwrites its existing contents
"a"AppendAdds content at the end
"rb", "wb"Read/write binaryUsed 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

PYTHON
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.

PYTHON
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

PYTHON — EXAM PATTERN
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

PYTHON — EXAM PATTERN
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

PYTHON
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

PYTHON
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.

Exam caution: opening a file with mode "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.

PYTHON — WRITE CSV
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])
PYTHON — READ CSV
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.

PYTHON
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

ModeMeaning
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.

PYTHON — WRITE A RECORD
import pickle

record = [101, "Meera", 91]
with open("student.dat", "wb") as f:
    pickle.dump(record, f)
PYTHON — READ RECORDS UNTIL EOF
import pickle

try:
    with open("student.dat", "rb") as f:
        while True:
            record = pickle.load(f)
            print(record)
except EOFError:
    pass

EOFError 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

PYTHON — ILLUSTRATIVE 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.
PYTHON — BASIC STACK
stack = []
stack.append("Red")
stack.append("Blue")
stack.append("Green")
print(stack)
print("Popped:", stack.pop())
print(stack)
Output
['Red', 'Blue', 'Green']
Popped: Green
['Red', 'Blue']

12.1 Exam-ready push, pop and display functions

PYTHON
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

PYTHON — EXAM-STYLE QUESTION
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)
Output
[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 / issueTypical causeCorrection
SyntaxErrorMissing colon, unmatched bracket or invalid syntaxCheck punctuation and statement structure
NameErrorUsing a variable/function name that is not definedCheck spelling and scope
TypeErrorUnsupported operation for the given typesConvert compatible types or correct the operation
ValueErrorValid function, unsuitable value such as int("abc")Validate the input before conversion
IndexErrorList/string index is outside its valid rangeCheck length and indexing
KeyErrorAccessing a missing dictionary key with square bracketsUse get() when a missing key is expected
IndentationErrorInconsistent or missing indentationIndent blocks consistently
Infinite loopLoop condition never becomes falseUpdate the control variable or use a correct exit condition

Find the mistake

INCORRECT CODE
for i in range(1, 5)
    print(i)

Correction: place a colon after range(1, 5).

INCORRECT CODE
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.

1 mark • Output

Q1. Predict the output.

QUESTION
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.

1 mark • Identifier

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.

1 mark • String

Q3. What does this print?

QUESTION
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.

1–2 marks • List methods

Q4. Predict the output.

QUESTION
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.

2 marks • Trace a loop

Q5. Find the output.

QUESTION
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.

2 marks • String methods

Q6. What is the result?

QUESTION
word = "Mississippi"
print(word.count("ss"))
print(word.replace("ss", "X"))
Show solution

Answer:
2
MiXiXippi

The non-overlapping substring "ss" occurs twice. replace() replaces each matching occurrence.

2 marks • Dictionary

Q7. Predict the output.

QUESTION
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.

2–3 marks • Write a program

Q8. Write a function to count the vowels in a string.

Show solution
MODEL ANSWER
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.

3 marks • Lists

Q9. Write a program to find the maximum, minimum and average of numbers in a list.

Show solution
MODEL ANSWER
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.

3 marks • Function

Q10. Write a function that accepts a list and returns a new list containing only even numbers.

Show solution
MODEL ANSWER
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].

3 marks • Text file

Q11. Write a function to count how many times the word “python” occurs in a text file, ignoring case.

Show solution
MODEL ANSWER
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.

3 marks • Stack

Q12. Write a pop function that returns the top item, or displays “Stack Underflow” and returns None when empty.

Show solution
MODEL ANSWER
def pop_one(myStack):
    if len(myStack) == 0:
        print("Stack Underflow")
        return None
    return myStack.pop()

The empty check must occur before calling pop().

4–5 marks • Dictionary

Q13. Create a dictionary that records the frequency of each character in an input string.

Show solution
MODEL ANSWER
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.

4–5 marks • CSV

Q14. Read a CSV file and display records whose marks are at least 80.

Show solution
MODEL ANSWER
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.

4–5 marks • Binary file

Q15. A binary file stores records as [roll number, name, marks]. Display the records with marks above 90.

Show solution
MODEL ANSWER
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:
        pass

Index 2 refers to marks in the assumed record format. Handle end-of-file with EOFError as shown.

4–5 marks • Output + concept

Q16. Explain why this code fails.

QUESTION
t = (1, 2, 3)
t[0] = 9
Show 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() and partition().
  • 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.writer and convert numeric strings before arithmetic.
  • For binary files, know pickle.dump(), pickle.load(), wb, rb and EOFError.
  • For stacks, remember LIFO, push with append(), pop with pop(), 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.

Preparation tip: Solve a paper first without looking at the answer key. Then compare your code with the official marking scheme and practise the questions you missed again after a day. Understanding the trace is more valuable than memorising a single output.

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.