Skip to content
7 MIN LESSON · COMPUTER SCIENCE

Class 12 Advanced Python Revision: Complete Concepts and Practice

Computer Science — A thorough revision of Class 11 Python for the board exam: tokens, data types, mutable and immutable objects, operators and precedence, control flow, strings, lists, tuples and dictionaries with their methods, slicing, and output-prediction practice, with every example tested.

Big picture

The Class 12 Computer Science paper assumes complete command of Class 11 Python. Many questions are "predict the output" or "find the error", and they test small details: operator precedence, floor division with negatives, slicing, whether an object is mutable, and what a method returns.

This lesson revises everything in one place, with examples you can run. Type each example into Python and check the output yourself; that is the fastest way to build accuracy.

Learning goals

  • Identify Python tokens: keywords, identifiers, literals, operators and punctuators.

  • Distinguish mutable and immutable data types.

  • Evaluate expressions using operator precedence, including **, // and %.

  • Use if, for, while, break and continue correctly.

  • Use string, list, tuple and dictionary operations and methods.

  • Predict the output of short code fragments.

Core ideas

1. Tokens

Token

Meaning

Examples

Keywords

Reserved words with special meaning

if, else, for, while, def, return, True, None, import

Identifiers

Names given to variables, functions and so on

total, marks_1, _count (can't start with a digit, can't be a keyword, case-sensitive)

Literals

Fixed values

25, 3.14, 'hello', True, None

Operators

Symbols that perform operations

+, **, //, ==, and, in

Punctuators

Symbols that organise code

( ) [ ] { } , : ;

2nd_value and for are invalid identifiers; value_2 and _for are valid.

2. Data types and mutability

Type

Example

Mutable?

int, float, complex

5, 2.5, 3+4j

Immutable

bool

True, False

Immutable

str

'Python'

Immutable

tuple

(1, 2, 3)

Immutable

list

[1, 2, 3]

Mutable

dict

{'a': 1}

Mutable

set

{1, 2}

Mutable

Mutable objects can be changed in place; immutable ones can't. s[0] = 'J' on a string gives a TypeError.

Aliasing. Assignment doesn't copy a list; both names refer to the same object.

L = [1, 2, 3]
M = L
M.append(4)
print(L)          # [1, 2, 3, 4]

A tuple containing a list is immutable as a tuple, but the list inside can still change:

t = (1, 2, [3, 4])
t[2].append(5)
print(t)          # (1, 2, [3, 4, 5])

3. Operators and precedence

Precedence (high to low)

Operators

1

** (right to left)

2

Unary +x, -x

3

*, /, //, %

4

+, -

5

Relational: <, >, <=, >=, ==, !=

6

not

7

and

8

or

Tricky results (tested):

print(2 ** 3 ** 2)      # 512   (2 ** 9, since ** is right-associative)
print(7 // 2, -7 // 2)  # 3 -4  (floor division rounds down, towards minus infinity)
print(7 % 3, -7 % 3)    # 1 2   (result takes the sign of the divisor)
print(2 + 3 * 4 ** 2)   # 50    (4**2 = 16, 3*16 = 48, 2+48)
print(5 / 2)            # 2.5   (/ always gives a float)
print(not True or False and True)   # False
print(10 > 5 > 2)       # True  (chained comparison)
print('a' < 'B')        # False (ASCII: 'a' is 97, 'B' is 66)

Augmented assignment: x = 5; x += 3 * 2 gives x = 11.

4. Control flow

for i in range(1, 10, 3):     # 1, 4, 7
    if i == 7:
        break
    print(i, end=' ')         # prints: 1 4
  • range(start, stop, step) stops before stop.

  • break exits the loop; continue skips to the next iteration.

  • A loop's else block runs only if the loop ends without break.

n = 7
for d in range(2, n):
    if n % d == 0:
        print('Not prime')
        break
else:
    print('Prime')            # prints Prime

5. Strings

Strings are immutable sequences indexed from 0 (or from −1 at the end).

s = 'COMPUTER'
print(s[1:6:2])     # OPT  (indices 1, 3, 5)
print(s[::-1])      # RETUPMOC
print(s[-3:])       # TER
print('Py' * 3)     # PyPyPy

Method

Returns

Example

upper(), lower()

New string in upper/lower case

'abc'.upper() → 'ABC'

title(), capitalize()

Title case; first letter capital

'hello world'.title() → 'Hello World'

find(sub)

Index of first match, or −1

'banana'.find('n') → 2

count(sub)

Number of occurrences

'banana'.count('a') → 3

replace(a, b)

New string with replacements

'cat'.replace('c', 'b') → 'bat'

split(sep)

List of parts

'a,b,c'.split(',') → ['a', 'b', 'c']

join(seq)

String joined with separator

'-'.join(['a', 'b']) → 'a-b'

strip()

Removes leading and trailing whitespace

isdigit(), isalpha(), isalnum()

True/False tests

'123'.isdigit() → True

6. Lists

L = [10, 20, 30, 40]
L.append([50])        # adds ONE element (a list)
print(len(L))         # 5

Method

Effect

Returns

append(x)

Adds x as one element at the end

None

extend(seq)

Adds each element of seq

None

insert(i, x)

Inserts x at index i

None

remove(x)

Removes first occurrence of x

None

pop(i)

Removes and returns element at i (last if omitted)

The element

sort()

Sorts in place

None

sorted(L)

Returns a new sorted list

New list

reverse()

Reverses in place

None

index(x), count(x)

Position, number of occurrences

int

A common trap: L = L.sort() sets L to None, because sort() returns None.

List comprehension: [i * i for i in range(4)] gives [0, 1, 4, 9].

7. Tuples and dictionaries

Tuples are immutable; a single-element tuple needs a comma: (5,). They support indexing, slicing, count() and index().

Dictionaries store key–value pairs; keys must be immutable (strings, numbers, tuples) and unique.

d = {'a': 1, 'b': 2}
d['c'] = 3              # add a new pair
print(len(d))           # 3
print(d.get('z', 0))    # 0 (default when key is missing; d['z'] would raise KeyError)

Method

Returns

keys(), values(), items()

Views of keys, values, (key, value) pairs

get(k, default)

Value for k, or default

update(d2)

Adds or replaces pairs from d2

pop(k)

Removes k and returns its value

del d[k]

Removes k

8. Type conversion and input

  • int('12') + 3 gives 15; int('12.5') gives a ValueError.

  • input() always returns a string; convert it with int() or float().

  • type(5/2) is <class 'float'>.

A reliable routine for output questions

  1. Trace the code line by line, writing variable values in a table.

  2. Apply precedence carefully: ** first (right to left), then * / // %, then + -, then comparisons, then not, and, or.

  3. For slicing, list the indices: start, start + step … up to (but not including) stop.

  4. For lists, remember aliasing and that append, sort and reverse return None.

  5. Check end= and sep= in print() for spacing.

Connections that matter

  • Functions and recursion builds on these data types and control structures.

  • Stack data structure uses lists with append() and pop().

  • File handling and Python–SQL connectivity use strings, lists and dictionaries heavily.

Common mistakes

  • Treating ` as left-associative.** 2 3 2` is 512, not 64.

  • Assuming `-7 // 2` is −3. It is −4.

  • Changing a string in place. Strings are immutable.

  • Expecting `append()` to add several elements. Use extend().

  • Forgetting that `range()` excludes the stop value.

Revision checklist

  • I can identify valid and invalid identifiers.

  • I can classify types as mutable or immutable and explain aliasing.

  • I can evaluate expressions with correct precedence.

  • I can use loops with break, continue and else.

  • I can use string, list, tuple and dictionary methods and slicing.

  • I can predict outputs accurately.

Practise this topic →

Discussion

Sign in to join the discussion.

Sign in

No comments yet. Be the first to share your thoughts.