Skip to content
Computer ScienceCBSE Class 12 · Chapter 1

Revision of Python Topics from Class XI: CBSE Class 12 Computer Science

Updated 14 October 2026 · Fact-checked

This chapter revises the Class XI Python you need for the Class 12 board paper: data types and mutability, operators and precedence, if and loops, strings, lists, tuples, dictionaries and the math, random and statistics modules. Board questions test it through output prediction, error correction, possible-output (random) questions and short programs.

What Revision of Python Topics from Class XI is about

Revision of Python topics from Class XI is the first chapter of Unit 1, Computational Thinking and Programming - 2. There is no new theory here, but almost every program in the Class 12 paper stands on it: a file-handling function still needs a loop and string methods, a stack program still needs list methods, and the Python-SQL program still needs a tuple from fetchone().

The board does not ask "explain a list". It gives you code and asks what it prints, which line is wrong, which outputs are possible with random, or asks for a short program. So the skill to build is tracing: running the code in your head line by line and writing down every variable as it changes.

The topics to revise are:

  • data types (int, float, complex, bool, str, list, tuple, dict, None) and which are mutable
  • operators, especially //, % and ** with negative numbers, precedence and the short-circuit behaviour of and and or
  • flow of control: if-elif-else, for with range(), while, break and continue
  • strings: indexing, slicing and methods such as split(), find(), replace(), count(), join(), title()
  • lists: slicing, aliasing, append(), extend(), insert(), pop(), remove(), sort() and sorted()
  • tuples and dictionaries: immutability, get(), items(), update(), pop(), setdefault(), fromkeys()
  • modules: math, random and statistics

Work through the key concepts with a pencil: write a trace table for every example before reading the answer.

Weightage: This chapter is part of Unit 1, Computational Thinking and Programming - 2, which carries 40 of the 70 theory marks together with Functions, Exception Handling in Python, File Handling in Python and Stack.Source: CBSE Computer Science (083) syllabus 2026-27, distribution of marks, Unit 1 Computational Thinking and Programming - 2

Key concepts

Data types and mutability
NCERT section Class XI NCERT 5.7 (data types), 8.3, 9.2, 10.1

Every value in Python has a type. Numbers (int, float, complex), bool, str, tuple and None are immutable: an operation that seems to change them actually builds a new object. list and dict are mutable: they can be changed in place. Dictionary keys must be immutable, so a list can never be a key, while a tuple can. A tuple holding a list is still a tuple: you cannot replace its items, but the list inside can grow.

Worked example

Which of these statements raise an error? s = 'abc'; s[0] = 'A' (i), L = [1, 2]; L[0] = 5 (ii), t = (1, [2, 3]); t[1].append(4) (iii), d = {[1, 2]: 'x'} (iv)

Try it first, then show the solutionSolution
  1. (i) A string is immutable, so item assignment fails: TypeError.
  2. (ii) A list is mutable: L becomes [5, 2]. No error.
  3. (iii) The tuple is not changed (it still holds the same list object); the list inside grows, t becomes (1, [2, 3, 4]). No error.
  4. (iv) A list is unhashable, so it cannot be a key: TypeError.

Answer: (i) and (iv) raise TypeError; (ii) and (iii) run.

Arithmetic operators and precedence
NCERT section Class XI NCERT 5.8, 5.9

Precedence from highest to lowest: **, then unary -, then * / // %, then + -, then relational operators, then not, and, or. Operators of the same level work left to right, except **, which works right to left: 2 ** 3 ** 2 is 2 ** 9 = 512. / always gives a float (8 / 2 is 4.0). // gives the floor (rounds towards minus infinity), so -7 // 2 is -4, and % takes the sign of the divisor, so -7 % 2 is 1 and 7 % -2 is -1. The rule that ties them: a == (a // b) * b + a % b.

Worked example

Evaluate: (a) 10 - 4 * 2 // 3 + 5 % 3 (b) -7 // 2, -7 % 2 (c) 2 ** 3 ** 2

Try it first, then show the solutionSolution
  1. (a) *, // and % first, left to right: 4 * 2 = 8, 8 // 3 = 2, 5 % 3 = 2. Then 10 - 2 + 2 = 10.
  2. (b) -7 / 2 = -3.5; the floor of -3.5 is -4. Check: (-4) * 2 + r = -7 gives r = 1.
  3. (c) Right to left: 3 2 = 9, then 2 9 = 512.

Answer: (a) 10 (b) -4 1 (c) 512

Relational and logical operators (short-circuit)
NCERT section Class XI NCERT 5.8.3

Relational operators can be chained: 1 < x < 5 means 1 < x and x < 5. The logical operators do not always give True or False: x or y returns x if x is truthy, else y; x and y returns x if x is falsy, else y. Falsy values are 0, 0.0, '', [], (), {}, None and False; everything else is truthy. Python stops evaluating as soon as the result is known (short-circuit), so 0 and 1/0 gives 0 without an error. not binds tighter than and, which binds tighter than or.

Worked example

Predict the output: print(0 or 'Hi', 3 and 0, '' or [] or 'x') and print(not 5 > 3 or 2 > 1 and 0)

Try it first, then show the solutionSolution
  1. 0 or 'Hi': 0 is falsy, so the result is 'Hi'.
  2. 3 and 0: 3 is truthy, so the result is the second operand, 0.
  3. '' or [] or 'x': both '' and [] are falsy, so 'x'.
  4. Second line: not 5 > 3 is False; 2 > 1 and 0 is True and 0, which is 0; False or 0 is 0.

Answer: Hi 0 x
0

Flow of control: if, for, while, break and continue
NCERT section Class XI NCERT 6.3-6.5

range(start, stop, step) stops before stop. break leaves the innermost loop at once; continue skips the rest of the current pass and goes to the next one. After a for loop ends (normally or by break), the loop variable keeps its last value. In a while loop, check where the variable changes: before or after the print decides the output.

Worked example

Predict the output:

x = 10
while x > 0:
    x -= 3
    if x % 2 == 0:
        continue
    print(x, end=' ')
Try it first, then show the solutionSolution
  1. Pass 1: x = 7, odd, prints 7.
  2. Pass 2: x = 4, even, continue (nothing printed).
  3. Pass 3: x = 1, odd, prints 1.
  4. Pass 4: x = -2, even, continue. Now x > 0 is False, so the loop ends.

Answer: 7 1

Strings: indexing, slicing and methods
NCERT section Class XI NCERT 8.2-8.7

A string of length n has indices 0 to n-1 and -1 to -n. A slice s[a:b:c] starts at a, stops before b, steps by c; a missing a or b means "from the end in the direction of the step", and a slice never raises IndexError (s[10:] on a short string is just ''). Methods return new strings and never change s: upper(), lower(), title(), capitalize(), strip(), replace(old, new[, count]), split([sep]), sep.join(list), partition(sep). Searching: find() returns -1 when the text is absent, but index() raises ValueError. count() counts non-overlapping occurrences. Tests: isalpha(), isdigit(), isalnum(), isupper(), islower(), isspace(), startswith(), endswith().

Worked example

If s = 'Board Exam 2027', find s[2:8], s[-4:], s[::-2], s.split('a') and s.find('a').

Try it first, then show the solutionSolution
  1. Index the characters: B0 o1 a2 r3 d4 (space)5 E6 x7 a8 m9 (space)10 2(11) 0(12) 2(13) 7(14).
  2. s[2:8] takes indices 2 to 7: 'ard Ex'. s[-4:] is the last four characters: '2027'.
  3. s[::-2] starts at index 14 and goes back two at a time: 14, 12, 10, 8, 6, 4, 2, 0, giving '70 aEdaB'.
  4. split('a') cuts at each 'a' and drops it: ['Bo', 'rd Ex', 'm 2027']. find('a') gives the first index, 2.

Answer: 'ard Ex', '2027', '70 aEdaB', ['Bo', 'rd Ex', 'm 2027'], 2

Lists: methods, slicing and aliasing
NCERT section Class XI NCERT 9.2-9.7

append(x) adds one item at the end; extend(seq) adds every item of seq; insert(i, x) puts x before index i; pop() removes and returns the last item (or the item at an index); remove(x) deletes the first x (ValueError if absent); sort() sorts in place and returns None, while sorted(L) returns a new list. Aliasing: M = L gives a second name for the same list, so a change through M shows in L. A copy (L[:], list(L) or L.copy()) is a separate list. L = L + [4] builds a new list and rebinds L, but L += [4] changes the list in place, so an alias sees it.

Worked example

Predict the output:

L = [10, 20, 30, 40]
M = L
M.append(50)
N = L[:]
N.append(60)
print(L, N)
print(L.pop(), L.pop(0), L)
Try it first, then show the solutionSolution
  1. M is an alias of L, so appending 50 through M changes L: [10, 20, 30, 40, 50].
  2. N is a copy of that list; appending 60 changes only N: [10, 20, 30, 40, 50, 60].
  3. Arguments are evaluated left to right: L.pop() returns 50, then L.pop(0) returns 10, leaving [20, 30, 40].

Answer: [10, 20, 30, 40, 50] [10, 20, 30, 40, 50, 60]
50 10 [20, 30, 40]

Tuples and dictionaries
NCERT section Class XI NCERT 10.1-10.6

A tuple is an ordered, immutable sequence. A one-item tuple needs a comma: (5,) is a tuple, (5) is just the int 5. Tuples support indexing, slicing, +, *, in, len(), count() and index(), and unpacking (a, b = b, a swaps). A dictionary maps unique, immutable keys to values. Assigning to an existing key replaces its value; to a new key adds a pair. d[k] raises KeyError for a missing key but d.get(k) returns None (or a default you give). Iterating over a dictionary gives its keys in insertion order. Useful methods: keys(), values(), items(), update(), pop(k), popitem(), setdefault(k, v), dict.fromkeys(keys, v), clear(), copy().

Worked example

Predict the output:

D = {'A': 1, 'B': 2, 'C': 3}
L = []
for k in D:
    D[k] = D[k] * 2
    L.append(k * D[k])
print(D)
print(L)
Try it first, then show the solutionSolution
  1. k = 'A': D['A'] becomes 2; 'A' * 2 = 'AA' is appended.
  2. k = 'B': D['B'] becomes 4; 'BBBB' is appended.
  3. k = 'C': D['C'] becomes 6; 'CCCCCC' is appended. Changing values (not keys) while looping is allowed.

Answer: {'A': 2, 'B': 4, 'C': 6}
['AA', 'BBBB', 'CCCCCC']

Modules: math, random and statistics
NCERT section Class XI NCERT 7.5 (modules)

Import with import math (then math.sqrt(16)) or from math import sqrt. math: sqrt() and pow() return floats, ceil() and floor() return ints, pi is a constant. random: random() gives a float in [0, 1); randint(a, b) gives an int from a to b including b; randrange(a, b) excludes b (like range). statistics: mean(), median() (middle of the sorted data, or the average of the two middle values) and mode(). In possible-output questions, list the smallest and largest value each random call can take, then test every option against those limits.

Worked example

What possible outputs can this code give? Also find the maximum value of start and the minimum value of end.

import random
A = ['RED', 'BLUE', 'GREEN', 'PINK']
start = random.randint(1, 2)
end = random.randint(2, 3)
for i in range(start, end + 1):
    print(A[i], end='#')

(a) RED#BLUE# (b) BLUE#GREEN#PINK# (c) GREEN#PINK# (d) PINK#

Try it first, then show the solutionSolution
  1. start can be 1 or 2; end can be 2 or 3. So printing begins at A[1] or A[2] and ends at A[2] or A[3].
  2. (a) starts at A[0]: impossible. (d) starts at A[3]: impossible.
  3. (b) is start = 1, end = 3. (c) is start = 2, end = 3. Both possible.
  4. Maximum start = 2, minimum end = 2.

Answer: (b) and (c); maximum start = 2, minimum end = 2.

Revision of Python Topics from Class XI in real life

Each concept, met in an everyday situation. Read the situation, answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.

Dictionary frequency count

Suppose your school librarian logs the genre of every book borrowed in a week as a list such as ['Fiction', 'Science', 'Fiction', 'Comics', 'Fiction', 'Science'] and wants to know which genre is borrowed most.

Write Python code that builds a dictionary of counts from the list and prints the genre with the highest count.

Try it first, then show the solutionSolution
  1. Start with an empty dictionary and add 1 to the count of each genre, using get() so a new genre starts at 0.
  2. genres = ['Fiction', 'Science', 'Fiction', 'Comics', 'Fiction', 'Science']
    count = {}
    for g in genres:
        count[g] = count.get(g, 0) + 1
    print(count)
    top = max(count, key=count.get)
    print('Most borrowed:', top)
  3. count becomes {'Fiction': 3, 'Science': 2, 'Comics': 1}; max() with key=count.get compares the values and returns the key.

Answer: {'Fiction': 3, 'Science': 2, 'Comics': 1}
Most borrowed: Fiction

Memory hook: Counting anything = empty dictionary + get(key, 0) + 1.

List aliasing

Imagine two friends share one online shopping cart: both phones show the same cart, so an item added on one phone appears on the other. That is what cart2 = cart1 does in Python.

cart1 = ['pen', 'file']; cart2 = cart1; cart2.append('ink'); cart3 = cart1[:]; cart3.append('bag'). What are cart1, cart2 and cart3?

Try it first, then show the solutionSolution
  1. cart2 = cart1 does not copy; both names refer to the same list, so 'ink' is added to it.
  2. cart3 = cart1[:] makes a separate copy of ['pen', 'file', 'ink']; adding 'bag' changes only cart3.

Answer: cart1 = cart2 = ['pen', 'file', 'ink']; cart3 = ['pen', 'file', 'ink', 'bag']

Memory hook: = shares the cart; [:] gives you your own cart.

random.randint() range

Suppose a quiz app picks a question number with random.randint(1, 20) and a bonus round with random.randrange(1, 4).

What values can each call give, and could the bonus round ever be 4?

Try it first, then show the solutionSolution
  1. randint(1, 20) includes both ends, so 1 to 20.
  2. randrange(1, 4) works like range(1, 4): 1, 2 or 3, so 4 is never chosen.

Answer: Question number 1-20; bonus round 1-3; never 4.

Memory hook: randINT is INclusive; randRANGE behaves like RANGE.

Topics in this chapter

Revision of Python Topics from Class XI: syntax and key facts

Operator precedence (high to low)
** > unary - > * / // % > + - > relational (< <= > >= == !=, in, is) > not > and > or
Same level: left to right, except **, which is right to left.
Floor division and remainder
a == (a // b) * b + a % b; // rounds down (towards minus infinity); % takes the sign of b
-7 // 2 = -4 and -7 % 2 = 1; 7 // -2 = -4 and 7 % -2 = -1.
Slicing
seq[start:stop:step]: from start up to stop - 1; negative step walks backwards; seq[::-1] reverses
Out-of-range slices give an empty result, never an error; out-of-range indexing raises IndexError.
range()
range(stop), range(start, stop), range(start, stop, step): stop is never included
range(10, 0, -3) gives 10, 7, 4, 1.
random functions
randint(a, b)a to b inclusive
randrange(a, b)a to b - 1
random()0.0 up to but not including 1.0
int(random.random() * n) gives 0 to n - 1.
find() versus index()
s.find(x) returns -1 if x is absent; s.index(x) raises ValueError
Lists have index() but no find().
Falsy values
0, 0.0, '', [], (), {}, None, False
x or y returns the first truthy operand (or the last one); x and y returns the first falsy operand (or the last one).

How the board asks Revision of Python Topics from Class XI

The question patterns to expect, and the method that works for each.

Question typeHow it is askedMethod
Predict the outputA short program with a loop over a string, list or dictionary (1-3 marks); sometimes in Section A as an MCQ.Make a trace table with one column per variable and one row per pass of the loop; write the printed text exactly, including end= separators and quotes or brackets that print() shows for lists and dictionaries.
Find and correct the errorsCode with three or four syntax or logical errors; rewrite it with each correction underlined (2 marks).Check, line by line: colons after if/for/while/def/else, matched brackets, == in conditions, keyword spelling and case (for, True), indentation, and type mismatches such as input() used as a number.
Possible outputs with randomFour options, choose the possible ones and state the maximum or minimum value a variable can take (2 marks).Write the full range of each random call (randint includes the upper end), then reject any option that needs a value outside the range or prints in the wrong order.
Short program on strings, lists or dictionariesCount, filter or rebuild data: e.g. count vowels, swap case, frequency of characters, names above average (2-3 marks).Write the input, the loop, the condition and the output as four separate lines of thought; use get(k, 0) + 1 for counting in a dictionary.
Evaluate an expressionOne-mark MCQ: value of an expression with mixed operators, or which statement raises an error.Apply precedence step by step and write the intermediate value after each operator; watch ** (right to left), // and % with negatives, and / giving a float.
Assertion-reason on data typesAn assertion about mutability, aliasing or a method's return value with a reason.Test the assertion with a tiny example in your head; then check whether the reason is the cause of the assertion, not just a true fact.

Tricks to remember Revision of Python Topics from Class XI

Short memory aids. Say each one aloud once, then use it on a question the same day.

  • PEMDAS for Python: "Power, Unary, Multiply, Add, Compare, Not, And, Or"

    Read it as "Please Use My Advice, Children Never Act Odd".

    Use it when: Order of evaluation in any expression question.

  • Floor means floor

    // always rounds towards the floor (down the number line), never towards zero: -3.5 goes to -4.

    Use it when: Negative floor division and remainder questions.

  • find is forgiving, index is strict

    find() quietly says -1; index() shouts ValueError.

    Use it when: Error-spotting and output questions on strings.

  • Comma makes the tuple

    It is the comma, not the bracket, that makes a tuple: t = 5, is a tuple; (5) is not.

    Use it when: type() and single-item tuple questions.

  • OR finds the first True, AND finds the first False

    or returns the first truthy value it meets; and returns the first falsy value it meets; if none, the last operand.

    Use it when: Output questions with and/or between non-Boolean values.

  • sort() says nothing

    L.sort() sorts in place and returns None, so print(L.sort()) prints None; sorted(L) hands you a new list.

    Use it when: Output and error questions on lists.

Revision of Python Topics from Class XI: board-level solved questions

Ordered from board level to HOTS. Cover the solution, write your own, then compare step by step.

Example 1: Swap case with a twist · 2 marks · Short answerHarder board level

Predict the output:

s = 'cbSE2027'
r = ''
for ch in s:
    if ch.isupper():
        r += ch.lower()
    elif ch.islower():
        r += ch.upper()
    elif ch.isdigit():
        r += str(int(ch) + 1)
print(r)
Try it first, then show the solutionSolution
  1. 'c' and 'b' are lowercase, so they become 'C' and 'B'.
  2. 'S' and 'E' are uppercase, so they become 's' and 'e'.
  3. Each digit is increased by 1: 2→3, 0→1, 2→3, 7→8.
  4. r is built in order: 'CB' + 'se' + '3138'.

Answer: CBse3138

Example 2: Short-circuit puzzle · 1 mark · MCQHOTS / competency

What does print(not 5 > 3 or 2 > 1 and 0) display? (a) True (b) False (c) 0 (d) 1

Try it first, then show the solutionSolution
  1. Relational operators come before not, and, or: 5 > 3 is True, 2 > 1 is True.
  2. not True is False. True and 0 returns 0 (the second operand).
  3. False or 0 returns its second operand, 0.

Answer: (c) 0

Example 3: Possible outputs with randint · 2 marks · Short answerHarder board level

Which of the outputs (i)-(iv) can this code produce? Give the least and greatest value of N.

import random
P = [3, 6, 9, 12, 15]
N = random.randint(1, 3)
for i in range(N, 0, -1):
    print(P[i], end='@')

(i) 6@3@ (ii) 9@6@ (iii) 12@9@6@ (iv) 6@

Try it first, then show the solutionSolution
  1. N can be 1, 2 or 3. range(N, 0, -1) gives N down to 1, so index 0 (value 3) is never printed.
  2. N = 1 prints 6@. N = 2 prints 9@6@. N = 3 prints 12@9@6@.
  3. (i) contains 3, which needs index 0: impossible.

Answer: (ii), (iii) and (iv); least N = 1, greatest N = 3.

Example 4: Alias or new list? · 2 marks · Short answerHOTS / competency

Predict the output:

a = [1, 2, 3]
b = a
a = a + [4]
print(a, b)
c = [1, 2, 3]
e = c
c += [4]
print(c, e)
Try it first, then show the solutionSolution
  1. a + [4] creates a new list [1, 2, 3, 4] and rebinds a; b still names the old list [1, 2, 3].
  2. c += [4] extends the existing list in place, so e (an alias) shows the change too.

Answer: [1, 2, 3, 4] [1, 2, 3]
[1, 2, 3, 4] [1, 2, 3, 4]

Example 5: Names above average · 3 marks · Short answerBoard level

The dictionary marks = {'Asha': 82, 'Ravi': 67, 'Meena': 91, 'Joy': 74} holds test marks. Write code to print the average and the names and marks of students who scored above it.

Try it first, then show the solutionSolution
  1. Average = total of the values / number of pairs.
  2. marks = {'Asha': 82, 'Ravi': 67, 'Meena': 91, 'Joy': 74}
    avg = sum(marks.values()) / len(marks)
    print(avg)
    for name in marks:
        if marks[name] > avg:
            print(name, marks[name])
  3. Total = 314, average = 78.5. Asha (82) and Meena (91) are above it.

Answer: 78.5
Asha 82
Meena 91

Example 6: Slicing and list assignment · 2 marks · Short answerHarder board level

Predict the output:

P = [3, 8, 1, 6]
P[1:3] = [0]
print(P, P * 2)
st = 'Python'
print(st[1:4] + st[-1] * 2, len(st[::3]))
Try it first, then show the solutionSolution
  1. Slice assignment replaces items 1 and 2 (8 and 1) with the single item 0: P = [3, 0, 6].
  2. P * 2 repeats the list: [3, 0, 6, 3, 0, 6].
  3. st[1:4] = 'yth'; st[-1] * 2 = 'nn'; joined: 'ythnn'.
  4. st[::3] takes indices 0 and 3: 'Ph', whose length is 2.

Answer: [3, 0, 6] [3, 0, 6, 3, 0, 6]
ythnn 2

Example 7: Tuple holding a list · 1 mark · Assertion-reasonHOTS / competency

Assertion (A): For t = (1, [2, 3]), the statement t[1].append(4) runs without error.
Reason (R): A tuple is immutable, but a mutable object stored inside it can still be changed.
(a) Both A and R are true and R is the correct explanation of A. (b) Both are true but R is not the correct explanation of A. (c) A is true but R is false. (d) A is false but R is true.

Try it first, then show the solutionSolution
  1. t[1] is a list; append() changes that list, not the tuple's slots. t becomes (1, [2, 3, 4]).
  2. R states exactly why this is allowed.

Answer: (a) Both A and R are true and R is the correct explanation of A.

Example 8: Longest word · 3 marks · Short answerHarder board level

Write a program that reads a sentence and prints the number of words and the longest word (the first one if there is a tie). Show the output for 'the quick brown fox jumps'.

Try it first, then show the solutionSolution
  1. split() with no argument gives the list of words.
  2. sentence = 'the quick brown fox jumps'
    words = sentence.split()
    longest = words[0]
    for w in words:
        if len(w) > len(longest):
            longest = w
    print(len(words), longest)
  3. > (not >=) keeps the first of equal-length words: 'quick', 'brown' and 'jumps' all have 5 letters, and 'quick' comes first. (In the exam, read the sentence with input().)

Answer: 5 quick

Case-study practice (Section E style)

Read the situation, then answer every part. In the board paper this is a 4-mark question split into 1 + 1 + 2 marks.

School canteen billing

Suppose the school canteen keeps its menu as a dictionary menu = {'samosa': 15, 'juice': 25, 'sandwich': 40} and records one order as a list of tuples order = [('samosa', 2), ('juice', 1), ('sandwich', 1)], each tuple being (item, quantity).

  1. (i) · 1 mark

    Write one statement that adds 'idli' with price 30 to the menu.

    Answer

    Answer: menu['idli'] = 30

    Assigning to a new key adds the pair.

  2. (ii) · 1 mark

    What does menu.get('pizza', 0) return, and why is get() safer than menu['pizza'] here?

    Answer

    Answer: 0; menu['pizza'] would raise KeyError because 'pizza' is not a key.

    get() returns the default when the key is missing.

  3. (iii) · 2 marks

    Write code to compute and print the total bill for the order.

    Answer

    Answer:

    menu = {'samosa': 15, 'juice': 25, 'sandwich': 40}
    order = [('samosa', 2), ('juice', 1), ('sandwich', 1)]
    total = 0
    for item, qty in order:
        total += menu[item] * qty
    print('Total =', total)
    Output: Total = 95

    Unpack each tuple into item and qty, look up the price and add price × quantity: 30 + 25 + 40 = 95.

Where the marks are

How a typical answer is split into step marks. Show every step: a right final answer alone rarely earns full marks.

Rewrite the code after removing all the errors, underlining each correction. [2 marks]

Num = int(input('Enter number')
For i in range(Num):
    if i%2=0:
        print(i)
    else
        print('odd')
(2 marks)

StepMarks
Closing bracket added: Num = int(input('Enter number'))0.5
For corrected to for0.5
= corrected to == in if i % 2 == 0:0.5
Colon added after else0.5

Write a program that reads a string and prints the number of uppercase letters, lowercase letters and digits in it. [3 marks] (3 marks)

StepMarks
Input of the string and three counters set to 00.5
Loop over every character0.5
Correct tests with isupper(), islower() and isdigit() and the counters increased1.5
Printing the three counts0.5

A dictionary MARKS stores names as keys and marks as values. Write code to (a) print the average marks and (b) build a list TOP of the names that scored above the average, then print it. [4 marks] (4 marks)

StepMarks
Average as sum(MARKS.values()) / len(MARKS)1
Printing the average0.5
Loop over keys (or items) with the comparison against the average1.5
Appending the name to TOP and printing TOP1

Write a menu-driven program for a dictionary PHONE (name: number) with options 1 add a contact, 2 search a name, 3 delete a name, 4 exit. [5 marks] (5 marks)

StepMarks
Loop that shows the menu and reads the choice until 4 is chosen1
Option 1: read name and number and add the pair1
Option 2: search with in (or get()) and a message when not found1
Option 3: delete with del or pop() only when the key exists1
Option 4 ends the loop; correct syntax and indentation throughout1

Where students lose marks in Revision of Python Topics from Class XI

The slips examiners see most often, and what to write instead.

  • Mistake: Treating L = L + [x] and L += [x] as the same when an alias exists

    + builds a new list and rebinds only L, while += extends the existing list, which the alias also sees.

    Wrong working

    a = [1, 2, 3]; b = a; a = a + [4]
    print(b) gives [1, 2, 3, 4]

    Right working

    a = a + [4] makes a new list, so b still refers to the old one
    print(b) gives [1, 2, 3]

    Do this: Ask: does this statement change the list object or make a new one? Only in-place changes (append, extend, +=, item assignment) show through an alias.

    Usually costs: 1 mark in an output question

  • Mistake: Writing the output of print() for a list or string without its exact format

    print() shows lists with square brackets, commas and quotes around strings, and a tuple with round brackets; a plain string prints without quotes.

    Wrong working

    print(['AA', 'BB']) gives AA BB

    Right working

    print(['AA', 'BB']) gives ['AA', 'BB']

    Do this: Copy the punctuation print() would show, including quotes inside lists and dictionaries, and respect end= and sep=.

    Usually costs: Half to 1 mark

  • Mistake: Taking randint's upper limit as excluded

    Students mix up randint(a, b), which includes b, with randrange(a, b), which excludes b.

    Wrong working

    randint(1, 3) can give 1 or 2

    Right working

    randint(1, 3) can give 1, 2 or 3

    Do this: Write the full list of values beside each random call before checking the options.

    Usually costs: The whole 2-mark possible-output question

  • Mistake: Rounding -7 // 2 towards zero

    In maths class -3.5 is often truncated to -3, but Python's floor division goes down to -4.

    Wrong working

    -7 // 2 = -3 and -7 % 2 = -1

    Right working

    -7 // 2 = -4 and -7 % 2 = 1 (because -4 × 2 + 1 = -7)

    Do this: Check every // and % answer with a == (a // b) * b + a % b.

    Usually costs: 1 mark

  • Mistake: Correcting only the obvious error in an error-finding question

    The question usually hides three or four errors: a missing colon, = for ==, a capital letter in a keyword, a missing bracket.

    Do this: Scan each line separately for each kind of error, and underline every change in the rewritten code: the marking scheme gives half a mark per correction.

    Usually costs: Half a mark per missed error

NCERT exercise guide: Revision of Python Topics from Class XI

What each exercise in the NCERT chapter tests, how to approach it, and a question of the same kind solved step by step. Questions here are written in our own words.

Class XI NCERT Chapter 5 (Getting Started with Python) exercises

What it tests: Identifiers, data types, operators, precedence and expression evaluation.

How to approach it: Evaluate operator by operator in precedence order and write each intermediate value; for invalid identifiers check the rules (letter or underscore first, no keywords, no special characters).

Same kind as the expression-evaluation exercises

Evaluate 15 // 4 * 2 + 3 ** 2 % 5 - 7 / 2.

Show the solutionSolution
  1. ** first: 3 ** 2 = 9.
  2. Then left to right among // * % /: 15 // 4 = 3; 3 * 2 = 6; 9 % 5 = 4; 7 / 2 = 3.5.
  3. Then 6 + 4 - 3.5 = 6.5.

Answer: 6.5

Class XI NCERT Chapter 6 (Flow of Control) exercises

What it tests: Programs with if-elif-else, for and while loops, nested loops, break and continue; patterns and series.

How to approach it: Decide what repeats and what stops the repetition; for patterns, let the outer loop count rows and the inner loop print each row.

Same kind as the pattern-printing exercises

Write a program to print

1
1 2
1 2 3
1 2 3 4
Show the solutionSolution
  1. The outer loop runs for rows 1 to 4; the inner loop prints 1 to the row number.
  2. for row in range(1, 5):
        for j in range(1, row + 1):
            print(j, end=' ')
        print()

Answer: The program above prints the four rows (each row ends with a trailing space).

Class XI NCERT Chapters 8-10 (Strings, Lists, Tuples and Dictionaries) exercises

What it tests: Output of methods, programs that count, search, reverse or rebuild strings, lists and dictionaries.

How to approach it: For output questions trace each method's return value; for programs, choose a dictionary when you need to count or look up by name.

Same kind as the dictionary programs

Write a program that counts how often each character occurs in 'MISSISSIPPI'.

Show the solutionSolution
  1. S = 'MISSISSIPPI'
    f = {}
    for ch in S:
        f[ch] = f.get(ch, 0) + 1
    print(f)
  2. Trace: M once, I four times, S four times, P twice; keys appear in the order first met.

Answer: {'M': 1, 'I': 4, 'S': 4, 'P': 2}

Practice questions on Revision of Python Topics from Class XI

Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.

  1. Q1 · 1 mark · Very short answerHarder board level

    Evaluate print(17 % -5, -17 // 5, 2 ** -1).

    Hint

    % takes the sign of the divisor; ** with a negative power gives a float.

    Answer

    -3 -4 0.5 (17 // -5 = -4 and -4 × -5 + (-3) = 17)

  2. Q2 · 1 mark · MCQBoard level

    Which of these is a valid dictionary? (a) {[1]: 'a'} (b) {(1, 2): 'a'} (c) {{1: 2}: 'a'} (d) {1: 'a', [2]: 'b'}

    Hint

    Keys must be immutable.

    Answer

    (b) {(1, 2): 'a'}; a tuple can be a key, a list or dictionary cannot.

  3. Q3 · 2 marks · Short answerBoard level

    Predict the output:

    T = (10, 20, 30, 40)
    print(T[1:3], T.index(30), 20 in T, len(T * 2))
    Hint

    Slicing a tuple gives a tuple.

    Answer

    (20, 30) 2 True 8

  4. Q4 · 2 marks · Short answerHarder board level

    Predict the output:

    n = 0
    for i in range(1, 10, 3):
        if i == 7:
            break
        n += i
    print(n, i)
    Hint

    range gives 1, 4, 7.

    Answer

    5 7 (n = 1 + 4; the loop breaks when i is 7, and i keeps that value)

  5. Q5 · 2 marks · Short answerHOTS / competency

    Predict the output:

    d = {'Ravi': 78, 'Meena': 90}
    print(d.setdefault('Kiran', 60), d.setdefault('Ravi', 50))
    print(d)
    Hint

    setdefault() adds the key only if it is missing and returns the value now stored.

    Answer

    60 78
    {'Ravi': 78, 'Meena': 90, 'Kiran': 60}

  6. Q6 · 3 marks · Short answerBoard level

    Write a program that reads a list of integers and builds a new list holding the squares of only the even numbers, in the same order. Show the result for [3, 4, 7, 10].

    Hint

    Loop, test x % 2 == 0, append x * x.

    Answer
    L = [3, 4, 7, 10]
    sq = []
    for x in L:
        if x % 2 == 0:
            sq.append(x * x)
    print(sq)

    Output: [16, 100]

  7. Q7 · 2 marks · Short answerHOTS / competency

    What possible outputs can this code give? (a) 30#40# (b) 10#20# (c) 20#30#40# (d) 40#

    import random
    L = [10, 20, 30, 40]
    k = random.randrange(1, 3)
    for i in range(k, 4):
        print(L[i], end='#')
    Hint

    randrange(1, 3) gives 1 or 2.

    Answer

    k = 1 prints 20#30#40#; k = 2 prints 30#40#. So (a) and (c).

  8. Q8 · 2 marks · Short answerHarder board level

    Rewrite the code after correcting the errors:

    def = {'a': 1, 'b': 2}
    for k in def.keys
        Print(k, def[k])
    Hint

    A keyword cannot be a name; methods need brackets.

    Answer
    d = {'a': 1, 'b': 2}
    for k in d.keys():
        print(k, d[k])

    Corrections: def is a keyword so it is renamed d (both uses); keys needs (); colon after the for line; Print should be print.

  9. Q9 · 3 marks · Short answerHarder board level

    Write a program that reads a string and prints it with every vowel replaced by '*'. For 'Computer', what is printed?

    Hint

    Build a new string; strings cannot be changed in place.

    Answer
    s = 'Computer'
    r = ''
    for ch in s:
        if ch in 'aeiouAEIOU':
            r += '*'
        else:
            r += ch
    print(r)

    Output: C*mp*t*r

  10. Q10 · 2 marks · Short answerHOTS / competency

    Predict the output:

    x, y = 5, 9
    x, y = y, x + y
    print(x, y)
    import statistics
    print(statistics.median([3, 1, 4, 1, 5]), statistics.mode([1, 2, 2, 3]))
    Hint

    The right side is evaluated fully before assignment; the median needs the sorted list.

    Answer

    9 14 (x + y uses the old x = 5)
    3 2 (sorted list 1, 1, 3, 4, 5 has middle value 3; 2 occurs most often)

Test your recall

Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.

  1. 1.What does 2 ** 3 ** 2 give, and why?Show answer

    512, because ** works right to left: 3 2 = 9, then 2 9.

  2. 2.Name three immutable and two mutable types.Show answer

    Immutable: int, float, str, tuple, bool. Mutable: list, dict.

  3. 3.What is the difference between s.find('x') and s.index('x') when 'x' is not in s?Show answer

    find() returns -1; index() raises ValueError.

  4. 4.How do you write a tuple with one element 7?Show answer

    (7,) or 7,; (7) is just the integer 7.

  5. 5.What does d.get('k', 0) return if 'k' is not a key?Show answer

    0, the default given; without a default it returns None. d['k'] would raise KeyError.

  6. 6.What does print([1, 2, 3].sort()) print?Show answer

    None, because sort() sorts in place and returns None.

  7. 7.What values can random.randrange(2, 8, 2) give?Show answer

    2, 4 or 6 (like range(2, 8, 2), 8 is excluded).

  8. 8.Give the output of 'hello world'.title() and 'hello world'.capitalize().Show answer

    'Hello World' and 'Hello world'.

  9. 9.What is the value of -17 % 5?Show answer

    3, because -17 // 5 = -4 and -4 × 5 + 3 = -17.

Best order to study it

  1. Data types and mutability, with the list of falsy values.
  2. Operators: precedence, ** right to left, // and % with negatives, and/or short-circuit.
  3. Flow of control: range(), break, continue, loop variable after the loop.
  4. Strings: indexing, slicing, then the methods in pairs (find/index, split/join, upper/lower, strip/replace).
  5. Lists: methods, slicing and aliasing; then tuples (single-item tuple, unpacking).
  6. Dictionaries: adding, updating, get(), items(), pop(), frequency counting; then math, random and statistics.

Quick revision checklist

The night before the exam: can you do each of these without looking?

  • Immutable: int, float, str, tuple, bool, None. Mutable: list, dict.
  • ** is right-associative; / always returns a float; // floors; % takes the divisor's sign.
  • or returns the first truthy operand, and the first falsy one; evaluation stops early.
  • range(a, b, c) never includes b; the loop variable keeps its last value after the loop.
  • Slices never raise IndexError; indexing past the end does.
  • find() gives -1, index() raises ValueError; split() with no argument splits on any whitespace.
  • append() adds one item, extend() adds each item; sort() returns None; sorted() returns a new list.
  • M = L is an alias; L[:], list(L) and L.copy() are copies.
  • (5,) is a tuple; (5) is an int. Dictionary keys must be immutable.
  • randint(a, b) includes b; randrange(a, b) excludes b.

Revision of Python Topics from Class XI: frequently asked questions

How many marks does revision of Class XI Python carry in the Class 12 board exam?

There is no separate figure for it. It is part of Unit 1, Computational Thinking and Programming - 2, which carries 40 of the 70 theory marks along with functions, exceptions, files and stacks. Revision topics appear mainly as Section A output and MCQ questions and Section B error-correction and output questions.

Which Class XI topics should I revise most for Class 12 Computer Science?

Strings and their methods, list methods and aliasing, dictionary methods, operator precedence with //, % and **, loops with break and continue, and the random module for possible-output questions. These are the building blocks of every Class 12 program.

Is the random module in the Class 12 syllabus?

The Class 12 syllabus asks you to revise the Class XI Python topics, and the Class XI syllabus includes the math, random and statistics modules. Possible-output questions based on random appear in CBSE sample papers.

Do I need to write the text of the correct option in an MCQ?

Yes. The CBSE paper instructs that for MCQs the text of the correct answer should also be written, not just the option letter.

How do I get better at output questions?

Trace on paper: draw a table with a column for each variable and a row for each pass of the loop, update it line by line, and only then write the output. Practise with nested loops, string slicing and dictionary loops.

Based on: CBSE Computer Science (083) syllabus 2026-27; NCERT Computer Science, Textbook for Class XI (Reprint 2026-27)