How to turn a problem into steps, and the steps into Python: values and their types, operators, decisions and loops, the four collections that hold data, and then, in Class XII, functions, exceptions, files and stacks.
19 chapters76 topics11-CS · Unit 211-IP · Unit 212-CS · Unit 1
Chapters 1 to 12 are the Class XI course (revised again in Class XII CS); chapters 13 to 19 are Class XII CS: functions, exceptions, files and stacks. Use the class filter at the top of the sidebar to see only your class. Grey >>> lines are the Python shell (interactive mode); everything else is a script run. The Methods button at the bottom right opens every string, list, tuple and dictionary method on one screen.
Chapter 1 of 19 · PSV
Problem Solving
A computer only follows instructions. Before writing any Python, you work out exactly what the problem is and the steps that solve it, and you draw or write those steps so that anyone can check them.
PSV.01 · Problem Solving
Steps for Problem-solving
11-CS12-CS
Problem solving is the process of finding the steps that turn the given input into the wanted output, and then getting a computer to carry them out. It always goes through the same five steps, in this order. Testing often finds a mistake, so the last steps repeat until the program is right.
The algorithm (filled) is the heart of it: once the steps are right, writing the code is mostly translation.
Read the problem until you can say three things clearly: what is given (the input), what is wanted (the output) and what rules connect them. For "find the average of three test marks": the input is three whole numbers, the output is one number, and the rule is add them, then divide by 3.
An algorithm is a finite set of clear, ordered steps that solves the problem. It is written in plain words or pictures, not in any one programming language, so the same algorithm can be coded in Python, C++ or Java. A good algorithm has a clear input and output, has no unclear step, and always stops.
Coding is writing the algorithm in a programming language, here Python. Each step of the algorithm becomes one or two lines. The written program is called the source code. Don't worry about the Python details yet: input() reads what the user types, int() turns it into a whole number and print() shows a result. PYB.08 explains all three.
Python · the algorithm as code
# Step 3, coding: average of three test marks
m1 = int(input('Test 1: '))
m2 = int(input('Test 2: '))
m3 = int(input('Test 3: '))
avg = (m1 + m2 + m3) / 3
print('Average =', round(avg, 2))
Testing means running the program on inputs whose correct answer you already know, and comparing. Choose normal values, edge values (0, the largest allowed) and wrong-looking values. A program is tested against what the problem asked for, not against what the programmer meant.
A mistake in a program is a bug; finding and removing it is debugging. Below, the program runs but the answer is wrong, because Python divides before it adds. Brackets fix it. The kinds of error are in ERR.01.
Learn the five steps in order: analyse, algorithm, code, test, debug. If asked "why write an algorithm before coding?", say: it shows the logic in plain steps that are easy to check, and it does not depend on any programming language.
PSV.02 · Problem Solving
Representation of Algorithms
11-CS12-CS
An algorithm can be shown in two standard ways: as a picture, a flowchart, or as structured English, pseudocode. Both describe the same steps; neither can be run by a computer directly.
A flowchart draws each step as a standard shape and joins the shapes with arrows that show the order. Every flowchart has one Start and at least one Stop.
Only the decision diamond has two exits. Every other symbol has one arrow out.
Four examples follow, from simple to harder. The same four problems are written as pseudocode and as Python below.
Example 1 · sequence: area of a rectangle
A sequence: no decision and no loop, so every box is visited exactly once.
Example 2 · one decision: even or odd
The decision tests n % 2 == 0 (the remainder when n is divided by 2). Yes and No lead to different boxes, and both paths join again before Stop.
One decision, two paths, joined again before Stop.
Example 3 · nested decisions: largest of three numbers
A decision inside a decision. For 12, 45, 27: a > b is No, so the right question is b > c, which is Yes, so big = 45.
Example 4 · a loop: sum of 1 to n
A loop in a flowchart is a decision whose Yes path goes back up to an earlier box. Something inside the loop (here i = i + 1) must change, so that the answer eventually becomes No.
A loop: the Yes path leads back to the same question. For n = 5 the body runs 5 times and s becomes 1 + 2 + 3 + 4 + 5 = 15.
Pseudocode ("false code") writes the steps in short English lines, using a few capitalised keywords such as INPUT, PRINT, IF … THEN … ELSE, WHILE and FOR, with indentation to show what belongs inside what. It has no strict grammar, so it is quick to write and easy to turn into any language.
Pseudocode
Means
In Python
INPUT x
Read a value
x = input()
PRINT x
Show a value
print(x)
x = expression
Work out and store
x = expression
IF … THEN … ELSE … END IF
Decide
if …:else:
WHILE … END WHILE
Repeat while a condition is true
while …:
FOR i = 1 TO n … END FOR
Repeat a counted number of times
for i in range(1, n + 1):
Example 1 · sequence: area of a rectangle
Pseudocode · not run
INPUT l, b
area = l * b
PRINT area
Python · the same steps
l = int(input('Length: '))
b = int(input('Breadth: '))
area = l * b
print('Area =', area)
Output · the user types 8 and 5
Length: 8
Breadth: 5
Area = 40
Example 2 · one decision: even or odd
Pseudocode · not run
INPUT n
IF n MOD 2 = 0 THEN
PRINT n, "is even"
ELSE
PRINT n, "is odd"
END IF
Python · the same steps
n = int(input('Enter a number: '))
if n % 2 == 0:
print(n, 'is even')
else:
print(n, 'is odd')
Output · the user types 37
Enter a number: 37
37 is odd
Example 3 · nested decisions: largest of three
Pseudocode · not run
INPUT a, b, c
IF a > b THEN
IF a > c THEN
big = a
ELSE
big = c
END IF
ELSE
IF b > c THEN
big = b
ELSE
big = c
END IF
END IF
PRINT big
Python · the same steps
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
if a > b:
if a > c:
big = a
else:
big = c
else:
if b > c:
big = b
else:
big = c
print('Largest =', big)
Output · the user types 12, 45, 27
a: 12
b: 45
c: 27
Largest = 45
Example 4 · a WHILE loop: sum of 1 to n
Pseudocode · not run
INPUT n
s = 0
i = 1
WHILE i <= n
s = s + i
i = i + 1
END WHILE
PRINT s
Python · the same steps
n = int(input('n: '))
s = 0
i = 1
while i <= n:
s = s + i
i = i + 1
print('Sum =', s)
Output · the user types 5
n: 5
Sum = 15
Example 5 · a FOR loop: multiplication table
Pseudocode · not run
INPUT n
FOR i = 1 TO 10
PRINT n, "x", i, "=", n * i
END FOR
Python · the same steps
n = int(input('Table of: '))
for i in range(1, 11):
print(n, 'x', i, '=', n * i)
Output · the user types 7
Table of: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Flowchart
Pseudocode
Form
A diagram of shapes and arrows
Lines of structured English
Good for
Seeing branches and loops at a glance
Long algorithms; close to real code
Drawback
Large and slow to draw, hard to change
No picture of the flow
Exam tip
Draw the right shape for each step: parallelogram for INPUT and PRINT, rectangle for a calculation, diamond for a question with Yes/No exits, rounded box for Start and Stop. A decision needs both exits labelled.
PSV.03 · Problem Solving
Decomposition
11-CS12-CS
Decomposition means breaking a large problem into smaller sub-problems, each simple enough to understand, solve and test on its own. The solutions are then put together to solve the whole problem. A school result system, for example, splits into reading marks, totalling, grading and printing.
One hard problem becomes four easy ones. In Class XII each part becomes a function.
Python · one part after another
# 1. input
name = 'Asha'
marks = [78, 85, 91, 66, 88]
# 2. process: total and percentage
total = sum(marks)
percent = total / len(marks)
# 3. process: grade
if percent >= 90:
grade = 'A1'
elif percent >= 75:
grade = 'A2'
else:
grade = 'B1'
# 4. output
print(name, total, percent, grade)
Output
Asha 408 81.6 A2
Each sub-problem can be written and tested separately, and by different people.
A mistake is easier to find, because it is inside one small part.
A solved part (such as "find the grade") can be reused in another program.
Exam tip
Define decomposition in one line ("breaking a complex problem into smaller, manageable sub-problems") and give an example with its parts. An answer without an example usually loses half the marks.
Chapter practice · PSV
Check your understanding
Predict the output (dry run)
n = 5
f = 1
i = 1
while i <= n:
f = f * i
i = i + 1
print(f)
120
f takes the values 1, 2, 6, 24, 120: it multiplies 1 × 2 × 3 × 4 × 5, the factorial of 5.
a, b, c = 12, 45, 27
big = a
if b > big:
big = b
if c > big:
big = c
print(big)
45
big starts at 12, becomes 45 at the first test, and 27 is not bigger, so it stays 45.
Which flowchart symbol shows the step "Is age ≥ 18?"
A diamond (decision).It asks a yes/no question and has two exits.
A program gives 0 for an average that should be 12.5. Which step of problem solving comes next?
Debugging.Testing found the bug; now find and fix it, then test again.
Self-check quiz
Which is the correct order of the steps of problem solving?
Understand the problem, plan the steps, write them in Python, then test and fix.
An algorithm must be:
An algorithm is language-independent and must always end.
Pseudocode cannot be run; it is a plain-English plan.
Breaking a big problem into smaller parts that are solved one by one is called:
Decomposition makes each part small enough to solve and test.
A program runs without any error message but prints a wrong total. Finding and removing this mistake is:
Any mistake in a program is a bug; removing it is debugging.
Your score
– / 6
Answer every question to see your score.
One-page revision
5 stepsanalyse → algorithm → code → test → debug
Algorithmfinite, clear, ordered steps; any language
Terminalrounded box: Start, Stop
Parallelograminput and output
Rectangleprocess: a calculation
Diamonddecision: Yes / No exits
Pseudocodestructured English, not run
Testingknown inputs, compare with expected
Bug · debugginga mistake · finding and fixing it
Decompositionbig problem → small sub-problems
Chapter 2 of 19 · PYB
Python Basics
What Python is, the two ways to run it, how a program is laid out with indentation, the smallest pieces it is built from (characters, tokens, variables and comments), and how a program reads input and prints output.
PYB.01 · Python Basics
Introduction to Python
11-CS11-IP12-CS
Python is a high-level, general-purpose programming language created by Guido van Rossum and first released in 1991. Its name comes from the comedy show Monty Python's Flying Circus, not the snake. Python programs are run by the Python interpreter, which reads the program and carries it out one statement at a time.
The first program in any language prints a greeting. In Python it is one line: print() is a built-in function that shows on the screen whatever you put inside its brackets. Text goes in quotes.
Python · hello.py
print('Hello, World!')
Output
Hello, World!
Exam tip
For "write any two features of Python", pick ones you can explain in a line: interpreted (runs line by line), free and open source, portable, dynamically typed. Python files are saved with the extension .py.
PYB.02 · Python Basics
Execution Modes
11-CS11-IP12-CS
Python code can be run in two execution modes: interactive mode, one statement at a time in the Python shell, and script mode, a whole program saved in a file. IDLE, the editor that comes with Python, has both: the Shell window and the File → New File editor.
The interpreter is the same in both modes. What differs is how much code it gets at once, and whether the code is kept.
In interactive mode you type one statement after the >>> prompt and press Enter; Python runs it and shows the result straight away. If you type an expression, its value is shown even without print(). It is handy for testing a small idea, but nothing you type is saved.
In script mode you write the whole program in a file, save it with the extension .py, and run it (in IDLE: Run → Run Module, or F5). The program can be kept, edited and run again. A script shows only what print() prints: a bare expression such as a + 3 is worked out and thrown away.
Python · hello.py
# hello.py: typed in a file, saved, then run
name = 'Asha'
print('Hello,', name)
a = 5
a + 3 # a script shows nothing for this
print(a + 3) # print() is needed
Output · only two lines
Hello, Asha
8
Interactive mode
Script mode
Code is
Typed one statement at a time at >>>
Written in a file and saved as .py
Runs
Each statement as soon as Enter is pressed
The whole file, when you run it
Value of an expression
Shown automatically
Shown only with print()
Saved?
No; lost when the shell closes
Yes; can be edited and run again
Best for
Quick tests and checks
Real programs of many lines
Exam tip
"Differentiate interactive and script mode" needs two points: interactive runs one statement at a time and is not saved; script mode runs a saved file of many statements. Add that only interactive mode shows an expression's value without print().
PYB.03 · Python Basics
Structure of a Program
11-CS11-IP12-CS
A Python program is a sequence of statements, run from top to bottom. Statements contain expressions, statements that belong together form blocks, blocks are marked by indentation, and comments explain the code to people. One small program shows all five.
The shaded bits are what Python reads as structure: the colon that opens a block, and the indent that says which lines belong to it.
Python · the parts of a program
# Program: area of a rectangle
length = 12 # statement
width = 5 # statement
area = length * width # expression on the right
if area > 50: # header: ends with :
print('Large', area) # block of the if
else:
print('Small', area)
Indentation is the space at the start of a line. Python uses it to decide which statements belong to which block, so it is part of the grammar, not just neatness. The usual indent is 4 spaces. Every line of one block must have the same indent; going back to the left ends the block.
Python · correct indentation
marks = 72
if marks >= 33:
print('Pass') # inside the if block
print('Well done') # same indent
print('Checked') # back at the left: outside
Output
Pass
Well done
Checked
Python · missing indent
marks = 72
if marks >= 33:
print('Pass')
Output · the program does not run
File "main.py", line 3
print('Pass')
^
IndentationError: expected an indented block after 'if' statement on line 2
Python · indent with no reason
x = 5
print(x)
Output
File "main.py", line 2
print(x)
^
IndentationError: unexpected indent
An expression is any combination of values, variables and operators that Python can work out to a single value: length * width, area > 50, 'Py' + 'thon', even a single 5. How Python works out a long expression is in EXP.01.
A statement is one complete instruction that Python carries out: area = length * width (assignment), print('Large', area), an if. Normally one statement is written per line. An expression gives a value; a statement does something, and may contain expressions.
A block (or suite) is a group of statements that run together, such as the body of an if or a loop. A block always follows a header line that ends with a colon (if area > 50:, else:), and all its lines are indented by the same amount.
Text after a # is a comment: a note for people that Python ignores. Comments are covered in full in PYB.07.
Common mistake
Mixing tabs and spaces, or indenting a line that is not inside a block, gives an IndentationError. In "rewrite the code after removing errors" questions, check that every line after a : is indented, and that the colon itself is there.
PYB.04 · Python Basics
Python Character Set
11-CS12-CS
The character set is the set of characters Python accepts in a program. Every token (PYB.05) is made of these characters.
Name the five groups: letters, digits, special symbols, whitespace and other (Unicode) characters. \t and \n are written as two characters but stand for one whitespace character each.
PYB.05 · Python Basics
Python Tokens
11-CS11-IP12-CS
A token (lexical unit) is the smallest unit of a program that has meaning to Python. Before running a line, Python splits it into tokens, just as a sentence splits into words. There are five kinds.
Spaces are not tokens; they only separate tokens. The keyword if is filled because keywords are fixed by Python and can never be used as names.
A keyword is a reserved word with a fixed meaning in Python, such as if, for, while, def, import. A keyword cannot be used as a variable name. All keywords are lowercase except True, False and None. The keyword module lists them:
Python · every keyword
import keyword
words = keyword.kwlist
print(len(words), 'keywords')
for i in range(0, len(words), 6):
print(*words[i:i + 6])
Output · Python 3.12
35 keywords
False None True and as assert
async await break class continue def
del elif else except finally for
from global if import in is
lambda nonlocal not or pass raise
return try while with yield
A literal is a fixed value written directly in the code. Python has string literals ('Pass', "25"), numeric literals (integer 25, float 3.5, complex 2+3j), Boolean literals (True, False) and the special literal None. Integers can also be written in binary (0b), octal (0o) or hexadecimal (0x).
An operator is a symbol or word that does an operation on values, called operands: in a + b, + is the operator and a and b are operands. Python has arithmetic, relational, logical, assignment, identity and membership operators; chapter OPR covers each.
A punctuator (delimiter) is a symbol that organises the code: it groups, separates or ends parts of statements. Common punctuators: ( ) [ ] { },:.;'"#@ and = (in assignment).
Exam tip
"Identify the tokens" questions: True, None and in are keywords; print, len and input are identifiers (names of built-in functions), not keywords. A quoted number such as "25" is a string literal.
PYB.06 · Python Basics
Variables
11-CS11-IP12-CS
A variable is a name that refers to a value stored in memory. It is created the first time a value is assigned to it with =; there is no separate declaration.
The same name can later refer to a value of a different type: this is dynamic typing. Python decides the type from the value at run time, and type() tells you what it is now. Several variables can be given values in one line.
Python shell · dynamic typing and multiple assignment
>>> x = 10
>>> type(x)
<class 'int'>
>>> x = 'ten'
>>> type(x)
<class 'str'>
>>> a, b, c = 1, 2.5, 'hi'
>>> p = q = 0
>>> print(a, b, c, p, q)
1 2.5 hi 0 0
a, b, c = 1, 2.5, 'hi' gives each name its own value, left to right.
p = q = 0 gives the same value to both names.
Using a variable before it has been given a value is a NameError.
In an assignment, the part on the left of = is the l-value: it must be a name (a place that can receive a value). The part on the right is the r-value: any expression, which is worked out first. A literal or an expression can never be an l-value.
Python first works out the r-value (x + 2 = 7), then makes the l-value y refer to it.
Python shell · only a name can be on the left
>>> x = 5
>>> y = x + 2
>>> y
7
>>> 5 = x
File "<stdin>", line 1
5 = x
^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
>>> x + 1 = y
File "<stdin>", line 1
x + 1 = y
^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
Exam tip
"What is dynamic typing?" Answer with an example: x = 10 makes x an int; later x = 'ten' makes it a str, with no error. "Why is 5 = x wrong?" Because 5 is a literal and cannot be an l-value.
PYB.07 · Python Basics
Comments
11-CS11-IP12-CS
A comment is text in a program that Python ignores. It is there for people: to say what the program does, why a step is needed, or who wrote it. Good comments make a program easier to read, check and change later.
Single-line comment: starts with # and runs to the end of the line. It can have a line to itself or follow code.
Multi-line note: Python has no special multi-line comment. Either start every line with #, or write a string in triple quotes ('''…''' or """…""") that is not assigned to anything; Python makes the string and throws it away. At the start of a function such a string is called a docstring.
A # inside quotes is part of the string, not a comment: print('#1') prints #1.
Python · both kinds of comment
# Area of a circle
r = 7 # radius in cm
area = 3.14 * r * r
'''
A string on its own, not given to any
variable, is skipped: a multi-line note.
'''
print('Area =', area)
Output · comments print nothing
Area = 153.86
Exam tip
To "comment out" a line means putting # in front of it, so it stops running without being deleted. In output questions, simply skip every commented line.
PYB.08 · Python Basics
Input and Output
11-CS11-IP12-CS
In the syllabus this topic belongs to Expressions, Type Conversion and Input-Output. It is taught here, at the end of Python Basics, because almost every later example reads input or prints a result.
A program reads data from the keyboard (the console) with input() and shows results with print(). In the outputs on this page, the text after a prompt such as First number: is what the user typed.
input(prompt) shows the prompt, waits for the user to type a line and press Enter, and returns what was typed as a string, always, even if it looks like a number. To do arithmetic, convert it with int(), which makes a whole number, or float(), which makes a decimal number. Conversion is covered fully in EXP.02.
Python · input gives a string
a = input('First number: ')
b = input('Second number: ')
print(a + b) # joins two strings
print(int(a) + int(b)) # adds two numbers
p = float(input('Principal: '))
r = float(input('Rate % : '))
t = float(input('Years: '))
si = p * r * t / 100
print('Simple interest =', si)
print('Amount =', p + si)
print(value1, value2, …, sep=' ', end='\n') shows any number of values. Between values it puts sep (a space by default), and after the last one it puts end (a newline by default). Changing end keeps the next print on the same line. print() with nothing inside prints an empty line.
a = input() then a + 5 is a TypeError, and a + a with 12 typed gives '1212'. Convert first: a = int(input()). In output questions, sep goes only between values, and end replaces the newline.
Chapter practice · PYB
Check your understanding
Predict the output
x = 7
x = x + 3
# x = x * 100
print('x =', x)
x = 10
The third line is a comment, so x is only increased once: 7 + 3 = 10.
Num = 4
num = 9
print(Num + num, Num * 2)
13 8
Num and num are different variables: 4 + 9 = 13, and 4 × 2 = 8.
a, b = 3, 8
a, b = b, a
print(a, b)
8 3
The right side (8, 3) is worked out first, then given to a and b: the values are swapped.
print('A', 'B', sep='*', end='#')
print('C')
A*B#C
sep puts * between A and B; end='#' replaces the newline, so C follows on the same line.
Which of these are valid identifiers: Roll_No, 1stName, else, _x9, pay-day?
Roll_No and _x9.1stName starts with a digit, else is a keyword, pay-day has a hyphen.
Self-check quiz
Python was developed by:
Guido van Rossum released Python in 1991. Ritchie made C, Gosling Java, Stroustrup C++.
In which mode does typing 5 + 3 alone show 8?
A script shows only what print() prints; the shell echoes every expression's value.
The extension of a Python script file is:
Python programs are saved as .py files.
Python marks a block of code by:
The lines of a block share the same indent, after a header ending in a colon.
Which is NOT part of Python's character set?
Tokens are made of characters; they are not a group of characters.
Which of these is a valid identifier?
Letters, digits and _ are allowed; it must not start with a digit or be a keyword.
In print("Sum", a + 5), "Sum" is a:
A fixed value written in the code is a literal; this one is a string literal.
Which of these is a keyword?
None is a keyword. print and input are names of built-in functions.
Which assignment gives an error?
The l-value must be a name; a literal like 5 cannot receive a value.
Which line is a comment in Python?
Python comments start with #. The others belong to C, Java or SQL.
The user types 5 for n = input(). What is n * 3?
input() returns the string '5', and a string times 3 repeats it.
What does print(1, 2, 3, sep='') show?
An empty separator joins the values with nothing between them.
Your score
– / 12
Answer every question to see your score.
One-page revision
PythonGuido van Rossum, 1991; interpreted
>>>interactive mode: one statement, not saved
.py · F5script mode: a saved file; print() to see
Indentation4 spaces; marks a block after a colon
Expression · statementgives a value · does something
Keywordreserved; 35 in Python 3.12; True False None
Identifierletters, digits, _; not a digit first
Literala fixed value: 25, 3.5, 'hi', True, None
Dynamic typinga name's type follows its current value
l-value · r-valueleft: a name · right: an expression
# · '''…'''comment · multi-line note (docstring)
input()always returns a str
int(input())read a whole number
sep=' 'between values
end='\n'after the last value
Chapter 3 of 19 · DTY
Data Types
Every value in Python has a type, which decides what it can hold and what can be done with it. This chapter maps out the built-in types and the one property examiners ask about most: whether a value can be changed in place.
The five groups in the syllabus, with the Python type name of each in blue. type(value) shows the name for any value.
DTY.01 · Data Types
Number
11-CS11-IP12-CS
Python has three numeric types: whole numbers (int), numbers with a fractional part (float) and complex numbers (complex). All three are immutable.
An integer (int) is a whole number, positive, negative or zero, with no decimal point: 25, -7, 0. Python integers have no size limit; they grow as large as memory allows.
A float is a real number written with a decimal point, or in exponent form: 2.5e3 means 2.5 × 10³. The result of / is always a float, even when it divides exactly. Floats are stored in binary to about 15–16 significant digits, so some decimals, like 0.1, are not exact.
A complex number has a real part and an imaginary part, written a + bj, where j is the square root of −1. .real and .imag give the two parts, always as floats, and abs() gives its size, √(a² + b²).
10 / 5 is 2.0, a float, not 2. In output questions, write the .0. Python uses j, not i, for the imaginary part, and 3 + 4j is one complex literal.
DTY.02 · Data Types
Boolean
11-CS11-IP12-CS
The Boolean type bool has exactly two values, True and False (capital first letter). Comparisons give Boolean results, and if and while decide using them. bool is a kind of integer: True counts as 1 and False as 0 in arithmetic.
bool(x) converts any value. Only "empty" or zero values are falsy (give False); everything else is truthy.
Anything else is truthy: -3, '0', ' ', 'False', [0]
Common mistake
bool('0') and bool('False') are True: they are non-empty strings. Only the empty string '' is falsy.
DTY.03 · Data Types
Sequence
11-CS11-IP12-CS
A sequence is an ordered collection of items, each at a numbered position called its index, starting from 0. All sequences support indexing s[i], slicing s[a:b], len(), +, * and in. Python has three sequence types in the syllabus.
Python shell · one of each
>>> s = 'Python'
>>> L = [10, 'ab', 3.5]
>>> t = (1, 2, 3)
>>> s[0], L[1], t[-1]
('P', 'ab', 3)
>>> len(s), len(L), len(t)
(6, 3, 3)
A list is a sequence of items of any types, in square brackets: [10, 'ab', 3.5]. Lists are mutable: items can be changed, added and removed. Full chapter: LST.
A tuple is like a list in round brackets, (1, 2, 3), but immutable: once made it cannot change. Full chapter: TUP.
str
list
tuple
Brackets
' ' or " "
[ ]
( )
Items
Characters only
Any values, mixed
Any values, mixed
Mutable?
No
Yes
No
Exam tip
The first item is at index 0 and the last at index len − 1, or −1 counting from the end. Indexes are the same idea in all three sequences.
DTY.04 · Data Types
None
11-CS11-IP12-CS
None is a special value meaning "no value" or "nothing here yet". Its type is NoneType, and it is the only value of that type. It is not 0, not False and not an empty string, though bool(None) is False.
Use it to make a variable before you have its real value: result = None.
A function that does not return anything gives back None. So does print(), and so do list methods that change the list in place, such as sort() and append().
Python · where None comes from
result = None
print(result, type(result))
L = [3, 1, 2]
x = L.sort() # sorts L, returns None
print(x)
print(L)
print(print('hi'))
Output
None <class 'NoneType'>
None
[1, 2, 3]
hi
None
Exam tip
print(print('hi')) prints two lines: hi from the inner call, then None, the value the inner print() returned. The same trap: print(L.append(2)) prints None.
DTY.05 · Data Types
Mapping
11-CS11-IP12-CS
A mapping links each key to a value, so you find a value by its key instead of by its position. Python's mapping type is the dictionary.
A dictionary (dict) holds key: value pairs in curly braces. Keys must be unique and of an immutable type; values can be anything. Dictionaries are mutable. Full chapter: DICT.
A dictionary is not a sequence: d[0] looks for the key 0, not the first item. Since Python 3.7 a dictionary keeps its items in the order they were added.
DTY.06 · Data Types
Mutable and Immutable Data Types
11-CS11-IP12-CS
A variable does not hold a value itself; it is a name that refers to an object in memory. An object of a mutable type can be changed in place, and stays the same object. An object of an immutable type can never change: every "change" makes a new object, and the name is moved to it.
Left: the int 5 is never changed; x is moved to a new object. Right: b = L does not copy the list; both names share one object, so a change through L shows through b.
Immutable
Mutable
int, float, complex, bool, str, tuple
list, dict (and set)
Item assignment gives a TypeError
Items can be changed, added, removed
Can be a dictionary key
Cannot be a dictionary key
id(x) gives an object's identity (its address in memory). If the id stays the same after a change, the object was changed in place.
Python · same object or new?
L = [1, 2, 3]
before = id(L)
L.append(4)
print(L, id(L) == before) # same object
s = 'cat'
before = id(s)
s = s + 's'
print(s, id(s) == before) # a new object
Output
[1, 2, 3, 4] True
cats False
Python shell · changing one item
>>> s = 'cat'
>>> s[0] = 'b'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> t = (1, 2)
>>> t[0] = 9
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> L = [1, 2]
>>> L[0] = 9
>>> L
[9, 2]
Python · a board question
a = [1, 2, 3]
b = a
a.append(4)
c = (5, 6, 7)
d = c + (8,)
print(b)
print(c, d)
Output
[1, 2, 3, 4]
(5, 6, 7) (5, 6, 7, 8)
b changed although only a was touched, because b = a made both names refer to one list. The tuple c is unchanged: c + (8,) made a new tuple d.
Exam tip
Define both with an example: "A list is mutable: L[0] = 9 changes it in place. A string is immutable: s[0] = 'b' raises TypeError." For Assertion–Reason: "list is mutable, because its elements can change while its id stays the same" is true, and R explains A.
/ always gives a float; // of two ints gives an int.
L = [4, 1]
print(L.append(2))
print(L)
None
[4, 1, 2]
append() changes L and returns None, so the first print shows None.
z = 2 - 5j
print(z.real + z.imag)
-3.0
.real is 2.0 and .imag is −5.0, both floats: 2.0 + (−5.0) = −3.0.
Self-check quiz
What is the type of 7 / 7?
The / operator always gives a float: 1.0.
Which is a valid complex literal in Python?
The imaginary part is a number followed by j.
bool(' ') (a single space) gives:
A space is a character, so the string is not empty and is truthy.
Which of these is NOT a sequence type?
A dictionary is a mapping: items are found by key, not by position.
The type of None is:
type(None) is <class 'NoneType'>.
What does print(L.sort()) show for L = [3, 1]?
sort() sorts L in place and returns None.
Which is a mutable data type?
Lists (and dictionaries) can be changed in place.
a = [1, 2]; b = a; b.append(3). What is a now?
b = a shares one list object, so a sees the change.
Which statement raises an error?
A string's characters can't be assigned. The last option makes a new string, which is fine.
Your score
– / 9
Answer every question to see your score.
One-page revision
intwhole number, no size limit
float3.5, 2.5e3; / always gives one
complex3 + 4j; .real .imag are floats
boolTrue, False; act as 1 and 0
Falsy0, 0.0, '', [], (), {}, None, False
Sequencestr, list, tuple: indexed from 0
Noneno value; type NoneType
dictkey: value; unique immutable keys
Immutableint float bool str tuple
Mutablelist dict: change in place, same id
b = ashares one object; no copy is made
type() · id()what type · which object
Chapter 4 of 19 · OPR
Operators
Operators do the work in an expression: they calculate, compare, combine conditions, store values and test what an object is or contains. Output questions lean on the tricky ones: // and %, and/or, and is versus ==.
OPR.01 · Operators
Arithmetic Operators
11-CS11-IP12-CS
Arithmetic operators do calculations on numbers. Python has seven. Two of them, + and *, also work on strings, lists and tuples: + joins and * repeats.
a // b divides and then rounds down to the whole number at or below the answer (the floor). a % b gives the remainder that goes with it, so that (a // b) * b + a % b == a always holds. If either number is a float, the result is a float (17.0 // 5 is 3.0).
With a negative number, "down" means towards minus infinity: −17 ÷ 5 = −3.4, whose floor is −4, not −3. Then the remainder is −17 − (−4 × 5) = 3. The result of % always has the sign of the divisor.
n = 5274
print('last digit :', n % 10)
print('without it :', n // 10)
print('tens digit :', n // 10 % 10)
print('is even? :', n % 2 == 0)
Output
last digit : 4
without it : 527
tens digit : 7
is even? : True
Exam tip
n % 10 is the last digit, n // 10 drops it, and n % 2 == 0 tests for even. These three appear in most digit programs (reverse, sum of digits, palindrome, Armstrong). Remember -7 // 2 is −4.
OPR.02 · Operators
Relational Operators
11-CS11-IP12-CS
Relational (comparison) operators compare two values and give True or False: == equal, != not equal, <, >, <=, >=.
Numbers compare by value: 5 == 5.0 is True. A number never equals a string: 5 == '5' is False.
Strings compare character by character, by Unicode code: 'A'–'Z' are 65–90 and 'a'–'z' are 97–122, so every capital letter is less than every small letter. The first difference decides, so '10' < '9' (because '1' < '9').
Comparisons can be chained: 1 < x < 5 means 1 < x and x < 5.
Lists and tuples compare item by item in the same way.
Comparing 'Z' < 'a' or 'apple' < 'Apple'? Compare the Unicode codes of the first different characters. Digits (48–57) < capitals (65–90) < small letters (97–122).
OPR.03 · Operators
Logical Operators
11-CS11-IP12-CS
Logical operators combine conditions. and is True only if both sides are true; or is True if at least one side is true; not reverses one value. They are worked out in the order not, then and, then or.
A
B
A and B
A or B
not A
True
True
True
True
False
True
False
False
True
False
False
True
False
True
True
False
False
False
False
True
Python shell
>>> True and False
False
>>> True or False
True
>>> not True
False
>>> 15 < 7 or not(29 < 19 and 25 > 74)
True
>>> 0 and 5
0
>>> 3 and 5
5
>>> 0 or 5
5
>>> '' or 'empty'
'empty'
>>> not 0
True
Short-circuit: and / or return one of their operands
Python stops as soon as it knows the answer. A and B: if A is falsy, the answer is A and B is never looked at; otherwise the answer is B. A or B: if A is truthy, the answer is A; otherwise B. So the result is one of the two values, not always True or False: 0 and 5 is 0, 3 and 5 is 5, 0 or 5 is 5. not always gives True or False.
Python · the right side is skipped
x = 0
# and stops at the first False part,
# so 10 / x is never worked out
print(x != 0 and 10 / x > 1)
print(x == 0 or 10 / x > 1)
Output · no ZeroDivisionError
False
True
Exam tip
For 15 < 7 or not(29 < 19 and 25 > 74): work out the brackets (False and False = False), then not (True), then or: False or True = True. If the question prints x and y with numbers, the answer is a number, not True/False.
OPR.04 · Operators
Assignment Operators
11-CS11-IP12-CS
The assignment operator= works out the expression on its right and makes the name on its left refer to the result (PYB.06). It is not a test for equality; that is ==.
Python shell · = stores, == compares
>>> a = 5
>>> a == 5
True
>>> a == 6
False
>>> if a = 5:
... print('five')
...
File "<stdin>", line 1
if a = 5:
^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
An augmented assignment joins an arithmetic operator with =: x += 5 means x = x + 5. There is one for each arithmetic operator: += -= *= /= //= %= **=. The variable must already have a value.
Python shell · one after another
>>> x = 10
>>> x += 5
>>> x
15
>>> x -= 3
>>> x
12
>>> x *= 2
>>> x
24
>>> x /= 4
>>> x
6.0
>>> x //= 2
>>> x
3.0
>>> x **= 3
>>> x
27.0
>>> x %= 5
>>> x
2.0
Python shell · there is no ++
>>> x = 5
>>> ++x
5
>>> x++
File "<stdin>", line 1
x++
^
SyntaxError: invalid syntax
Python has no ++ or --. ++x is just two unary plus signs, so it gives 5 and changes nothing; x++ is a syntax error. Write x += 1.
Exam tip
Once /= has run, the variable is a float, and so are the results of every later //=, **= and %= on it (6.0, 3.0, 27.0, 2.0 above). "Difference between = and ==" is a frequent 2-mark question: give the kind, what it does and one example of each.
OPR.05 · Operators
Identity Operators
11-CS11-IP12-CS
Identity operators test whether two names refer to the same object in memory, that is, whether their id() is the same. == asks a different question: do the two objects hold equal values?
b = a makes b a second name for a's list. c = [1, 2] builds a new list that happens to hold the same values.
x is not y is True when they are different objects, even if their values are equal.
Python · is versus ==
a = [1, 2]
b = a
c = [1, 2]
print(a == c, a is c)
print(a is b, a is not c)
x = None
print(x is None)
Output
True False
True True
True
Common mistake
Don't use is to compare numbers or strings. Python sometimes reuses one object for small ints and short strings, so is may seem to work and then fail for other values. Compare values with ==; keep is for None and for "same object?" questions.
OPR.06 · Operators
Membership Operators
11-CS11-IP12-CS
Membership operators test whether a value is present in a string, list, tuple or dictionary, and give True or False.
x in seq is True if x is one of the items. For strings it tests for a substring (any run of characters, case-sensitive). For a dictionary it looks only at the keys.
x not in seq is the opposite: True if x is not present.
Python shell
>>> 'y' in 'Python'
True
>>> 'Py' in 'Python'
True
>>> 'py' in 'Python'
False
>>> 3 in [1, 2, 3]
True
>>> [1] in [1, 2]
False
>>> 5 not in (1, 2)
True
>>> d = {'a': 1}
>>> 'a' in d
True
>>> 1 in d
False
Exam tip
1 in {'a': 1} is False: membership checks keys, not values (use 1 in d.values()). [1] in [1, 2] is False: the list holds 1, not the list [1]. Board programs often write if ch in 'aeiouAEIOU': to test for a vowel.
Chapter practice · OPR
Check your understanding
Predict the output
print(7 // 2, -7 // 2, 7 % 3, -7 % 3)
3 -4 1 2
−3.5 floors to −4. −7 % 3: −7 − (−3 × 3) = 2, with the divisor's sign.
a = 4
a += a * 2
a //= 5
print(a)
2
a += 8 makes 12 (the right side 4 × 2 is worked out first); 12 // 5 = 2.
x, y = 10, 0
print(x > 5 and y)
print(y or x)
print(not x == 10)
0
10
False
x > 5 is True, so and returns y (0). y is falsy, so or returns x. not (x == 10) is False.
print('5' + '3', '5' * 3, 5 * 3)
53 555 15
On strings + joins and * repeats; only 5 * 3 is arithmetic.
s = 'Kendriya'
print('end' in s, 'K' not in s)
True False
'end' is a substring of 'Kendriya'; 'K' is present, so not in is False.
Self-check quiz
What is -13 // 4?
−3.25 rounded down (towards minus infinity) is −4.
What is 19 % 4?
19 = 4 × 4 + 3, so the remainder is 3.
Which is True?
Every capital letter has a smaller code than every small letter: 'Z' (90) < 'a' (97).
What does 0 or 'yes' give?
0 is falsy, so or returns its second operand.
Which operator is worked out first in not a or b and c?
not, then and, then or: (not a) or (b and c).
After x = 7; x //= 2; x **= 2, x is:
7 // 2 = 3, then 3 ** 2 = 9.
x++ in Python:
Python has no ++ operator; use x += 1.
a = [5]; b = [5]. Which is True?
Two separate list objects with equal values.
For d = {'x': 10}, which gives True?
in checks the keys of a dictionary.
'th' in 'Python' gives:
'th' is a substring at positions 2–3.
Your score
– / 10
Answer every question to see your score.
One-page revision
/ · //float division · floor (rounds down)
% · **remainder (divisor's sign) · power
-7 // 2−4, and -7 % 2 is 1
n%10 · n//10last digit · drop the last digit
== != < > <= >=compare; give True / False
'Z' < 'a'codes: digits < capitals < small
not · and · orthe order they are worked out
0 and 5 · 0 or 50 · 5: and/or return an operand
x += 5x = x + 5; there is no ++
= vs ==assign vs compare
is · is notsame object? (same id)
in · not inpresent? dict: keys only
Chapter 5 of 19 · EXP
Expressions, Type Conversion and Input-Output
How Python decides which part of a long expression to work out first, and how values change from one type to another. The third part of this syllabus topic, input and output, is taught earlier, at the end of Python Basics (PYB.08), so that every example can use it.
EXP.01 · Expressions, Type Conversion and Input-Output
Expressions and Statements
11-CS11-IP12-CS
An expression is worked out to one value; a statement is an instruction that is carried out (PYB.03). total = 3 + 4 * 2 is an assignment statement whose right side, 3 + 4 * 2, is an expression with the value 11. When an expression has several operators, two rules decide the order: precedence and associativity.
Precedence says which operator goes first: an operator higher in the table is worked out before a lower one. Operators on the same row have equal precedence; associativity (next) decides between them. Brackets override everything.
Order
Operators
Meaning
1 (first)
( )
Brackets
2
**
Exponent, right to left
3
+x-x
Unary plus and minus
4
*///%
Multiply and divide
5
+-
Add and subtract
6
== != < > <= >=isin
Relational, identity, membership
7
not
Logical NOT
8
and
Logical AND
9 (last)
or
Logical OR
Assignment (=, += …) is lower still: the whole right side is worked out before anything is stored. Because ** is above unary minus, -2 ** 2 is -(2 ** 2) = −4.
When an expression has two operators of the same precedence, associativity decides which goes first. Almost every operator is left-associative: it is worked out from left to right. The one exception in the syllabus is **, which is right-associative: worked out from right to left. Associativity matters only when the order changes the answer, as it does for /, -, // and **.
Associativity puts the invisible brackets in: on the left for /, on the right for **. Brackets you write yourself always win.
To evaluate an expression by hand, find the operator with the highest precedence, work out just that part, rewrite the expression with its value, and repeat until one value is left. One board question, done that way:
The blue bar marks the part worked out at each step. The program on the right prints the same five values, so you can check each step.
Python · the steps, checked
# 10 - 3 ** 2 ** 2 + 144 / 12, step by step
print(2 ** 2) # 1. ** first, right to left
print(3 ** 4) # 2. the next **
print(144 / 12) # 3. / before + and -
print(10 - 81) # 4. + and - left to right
print(-71 + 12.0) # 5.
print(10 - 3 ** 2 ** 2 + 144 / 12)
2 ** 3 ** 2 is 512 (2 ** 9), not 64. 2 // 18 % 4 ** 2 + 3: ** first (16), then // and % left to right (2 // 18 = 0, 0 % 16 = 0), then + 3 = 3. If a / appears anywhere, the answer is a float: write 260.0, not 260.
EXP.02 · Expressions, Type Conversion and Input-Output
Type Conversion
11-CS11-IP12-CS
Type conversion (type casting) changes a value from one data type to another. Either you ask for it in the code (explicit), or Python does it on its own while working out an expression (implicit).
In explicit conversion the programmer calls a conversion function with the type's name: int(), float(), str(), bool() (also list(), tuple(), dict() in later chapters). int() of a float cuts off the decimal part, towards zero; it does not round. A string must look exactly like the number, or the result is a ValueError.
Python shell
>>> int('25') + 5
30
>>> int(3.99)
3
>>> int(-3.99)
-3
>>> float('3.5')
3.5
>>> float(7)
7.0
>>> str(25) + '5'
'255'
>>> int(True), bool(1)
(1, True)
>>> int('3.5')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.5'
>>> int('abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
In implicit conversion (coercion) Python converts a value by itself, when doing so loses nothing: an int meets a float and becomes a float; a bool becomes an int. Python never turns a number into a string or a string into a number on its own, so mixing them is a TypeError.
"Explain implicit and explicit conversion with an example each" is a regular 2-marker. Use the two examples in the table. int('3.5') fails; to get 3 from the string, write int(float('3.5')).
Chapter practice · EXP
Check your understanding
Predict the output
print(2 + 3 * 4 ** 2 // 5)
11
4 ** 2 = 16; 3 * 16 = 48; 48 // 5 = 9; 2 + 9 = 11. No /, so an int.
Python turns 4 into 4.0 by itself; the result is 6.5.
Which gives a ValueError?
int() needs a string that looks like a whole number.
Your score
– / 6
Answer every question to see your score.
One-page revision
Order() ** unary * / // % + - compare not and or
** associativityright to left: 2**3**2 = 512
Othersleft to right: 100/10/5 = 2.0
-2 ** 2−4: ** before unary minus
Any / usedthe answer is a float
Explicitint() float() str() bool(), by you
Implicitint + float → float, by Python
int(3.99)3: cuts off, does not round
Chapter 6 of 19 · ERR
Errors and Debugging
Programs go wrong in three different ways. Knowing which kind of error you are looking at tells you where to look for it, and it is how the board's "rewrite the code after removing all errors" questions are marked.
ERR.01 · Errors and Debugging
Types of Errors
11-CS11-IP12-CS
An error (bug) is anything that stops a program from running or from giving the right result. Debugging is finding and removing errors (PSV.01). Errors fall into three kinds, which Python finds at different times, or not at all.
The filled box is the hardest to find: Python gives no message for a logical error, so only testing (comparing with the expected answer) reveals it.
A syntax error breaks the grammar rules of Python: a missing colon, bracket or quote, a misspelt keyword, wrong indentation. Python checks the whole program before running it, so not even the first line runs; it reports the line number and a caret ^ near the problem. IndentationError is a kind of syntax error.
Python · missing colon
marks = 80
if marks > 33
print('Pass')
Output
File "main.py", line 2
if marks > 33
^
SyntaxError: expected ':'
Python · missing quote
print('Hello)
Output
File "main.py", line 1
print('Hello)
^
SyntaxError: unterminated string literal (detected at line 1)
Python shell · more syntax errors
>>> print 'Hello'
File "<stdin>", line 1
print 'Hello'
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
>>> x = 5 +
File "<stdin>", line 1
x = 5 +
^
SyntaxError: invalid syntax
>>> while True print(x)
File "<stdin>", line 1
while True print(x)
^
SyntaxError: invalid syntax
A logical error is a mistake in the logic: the program is valid Python and runs to the end, but gives the wrong output. Python cannot know what you meant, so it shows no message. Typical causes: a wrong operator or formula, wrong order of operations, a loop that runs one time too few, a wrong condition.
Python · range stops too early
total = 0
for i in range(1, 10): # should be range(1, 11)
total += i
print('Sum of 1 to 10 =', total)
Output · wrong, should be 55
Sum of 1 to 10 = 45
Python · fixed
total = 0
for i in range(1, 11):
total += i
print('Sum of 1 to 10 =', total)
A runtime error happens while the program is running, when a statement asks for something impossible: dividing by zero, using a name that has no value, converting 'five' to a number. The lines before it have already run; Python stops at that line and prints a traceback ending with the error's name. Runtime errors are also called exceptions (handled with try–except in Class XII).
Python · stops part-way
print('Start')
a = 10
b = 0
print(a / b)
print('End')
Output · 'End' is never printed
Start
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(a / b)
ZeroDivisionError: division by zero
Python shell · the common runtime errors
>>> 10 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> y + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
>>> '5' + 5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> int('five')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'five'
>>> L = [1, 2]
>>> L[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> d = {'a': 1}
>>> d['b']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'b'
>>> import maths
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'maths'
Error
Raised when
ZeroDivisionError
Dividing (/, //, %) by zero
NameError
Using a name that has not been given a value
TypeError
An operation on the wrong type: '5' + 5, s[0] = 'x'
ValueError
The type is right but the value is not: int('five')
IndexError
An index outside the sequence
KeyError
A key that is not in the dictionary
ModuleNotFoundError
Importing a module that does not exist
A board question: rewrite after removing the errors
"Ravi wrote a program to check whether a number is a palindrome. Rewrite it after removing the syntax and logical errors, and underline each correction." Running his code finds only the first syntax error. Python stops there, so you must read every line yourself.
Python · as given
n=int(input("Enter number:"))
temp=n
rev=0
while(n < 0):
dig==n%10
rev=rev*10+dig
n=n//10
if(temp=rev)
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
Output · only one error is reported
File "main.py", line 8
if(temp=rev)
^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
Line
Error
Kind
Correction
while(n < 0):
Loop never runs for a positive number
Logical
while n > 0:
dig==n%10
== compares; it does not store
Logical
dig = n % 10
if(temp=rev)
= instead of ==, and no colon
Syntax
if temp == rev:
Python · corrected
n = int(input('Enter number:'))
temp = n
rev = 0
while n > 0:
dig = n % 10
rev = rev * 10 + dig
n = n // 10
if temp == rev:
print('The number is a palindrome!')
else:
print("The number isn't a palindrome!")
Output · the user types 12321
Enter number:12321
The number is a palindrome!
Exam tip
In error-correction questions, check every line for: a missing colon after if/elif/else/for/while; = vs ==; capital letters in keywords and functions (Print, If, Def, false); missing brackets or quotes; range[0, 7] instead of range(0, 7); and wrong indentation. Write the full corrected code and underline only the changes.
Chapter practice · ERR
Check your understanding
Predict the output, or the error
L = [10, 20, 30]
print(L[1])
print(L[3])
20
Traceback (most recent call last):
File "main.py", line 3, in <module>
print(L[3])
IndexError: list index out of range
L[1] prints first; the indexes are 0–2, so L[3] is a runtime IndexError on line 3.
age = 15
print('Age: ' + age)
Traceback (most recent call last):
File "main.py", line 2, in <module>
print('Age: ' + age)
TypeError: can only concatenate str (not "int") to str
A string can only be joined to a string. Fix: str(age), or print('Age:', age).
Name the kind of error: avg = (a + b) / 3 in a program meant to average two numbers.
Logical error.It runs, but divides by the wrong number.
Name the kind of error: for i in range(5) print(i)
Syntax error.The colon is missing and the body must go on its own indented line.
Self-check quiz
An error that Python finds before running even the first line is a:
The whole program is checked for grammar first.
A program runs to the end but prints a wrong answer. The error is:
Python gives no message for a logical error.
int('12a') raises:
The type (str) is fine; the value can't be read as an int.
Which is a runtime error?
Division by zero is only found when that line runs. The first and third are syntax errors; the second is logical.
Which correction is right for if x = 10?
Compare with == and end the header with a colon.
Your score
– / 5
Answer every question to see your score.
One-page revision
Syntax errorgrammar broken; nothing runs
Runtime errorimpossible step; stops at that line
Logical errorruns, wrong answer; no message
Tracebackline number + error name
ZeroDivisionError/ // % by 0
NameErrorname has no value (or misspelt)
TypeErrorwrong type: '5' + 5
ValueErrorright type, bad value: int('x')
IndexError · KeyErrorno such index · no such key
Rewrite questionscolons, = vs ==, case, brackets, indent
Chapter 7 of 19 · FLOW
Flow of Control
The order in which a program's statements run. Normally it is top to bottom; if lets a program choose between paths, and for and while let it repeat. Loop output questions are among the most frequent in the board paper.
FLOW.01 · Flow of Control
Introduction to Flow of Control
11-CS11-IP12-CS
Flow of control is the order in which the statements of a program are carried out. Every program, however large, is built from just three kinds of flow. The blocks that belong to an if or a loop are marked by indentation (PYB.03).
Flow of control is about the order in which statements run, so first, the kinds of statement there are. Python has three: the empty statement, simple statements and compound statements. Conditional and looping statements are compound statements, and they are what this chapter is about.
A compound statement contains other statements in its indented block, simple or compound, which is how ifs and loops can be nested.
Type
What it is
Examples
Empty statement
A statement that does nothing. Used where Python's grammar needs a statement but there is nothing to do yet, such as an empty block
pass
Simple statement
A single line that does one thing
x = 5, print(x), n = int(input()), import math, break, continue
Compound statement
A header line ending in a colon, plus an indented block of other statements
if, if-else, if-elif-else (conditional); for, while (looping); also def and try in Class XII
Python · each kind, labelled
x = 7 # simple: assignment
print('x is', x) # simple: function call
if x % 2 == 1: # compound: conditional
print('odd')
for i in range(2): # compound: looping
print('round', i)
Output
x is 7
odd
round 0
round 1
A block can't be left empty: a comment doesn't count as a statement. pass keeps the program valid while a part is still to be written.
Python · pass fills an empty block
x = 5
if x > 0:
pass # nothing to do yet
for i in range(3):
pass
print('pass did nothing; no error')
Output
pass did nothing; no error
Python · without pass
x = 5
if x > 0:
# to do later
print('done')
Output · only a comment in the block
File "main.py", line 4
print('done')
^
IndentationError: expected an indented block after 'if' statement on line 2
The three kinds of flow
The test (filled diamond) is what makes flow conditional or iterative. In a loop, the "Yes" path leads back to the same test.
In conditional flow (selection, branching) a condition is tested and, depending on whether it is True or False, one block runs and another is skipped. Python uses if, if-else and if-elif-else (FLOW.02).
In iterative flow (looping, repetition) a block runs again and again, either once for each item of a sequence or while a condition stays True. Python uses for and while (FLOW.03). Each run of the body is one iteration.
Exam tip
Name the three constructs with their Python statements: sequential (plain statements), conditional (if, if-else, if-elif-else), iterative (for, while).
FLOW.02 · Flow of Control
Conditional Statements
11-CS11-IP12-CS
A conditional statement runs a block only when its condition is True. The condition is any expression; Python uses its truth value (DTY.02), so if n: means "if n is not zero". The header line ends with a colon, and the block under it is indented.
The simple if runs its block when the condition is True and does nothing otherwise. Either way, the program then carries on with the next unindented line.
With if alone, the No path does nothing: it skips the block and joins the program again below it.
Python · if
marks = 45
if marks >= 33:
print('Pass')
print('Done')
Output
Pass
Done
Python · absolute value
n = int(input('Enter a number: '))
if n < 0:
n = -n
print('Absolute value:', n)
if-else chooses between exactly two blocks: the if block when the condition is True, the else block when it is False. Exactly one of them always runs. else has no condition of its own.
Exactly one of the two blocks runs, never both and never neither, and then the paths join.
Python · divisibility
n = int(input('Enter a number: '))
if n % 5 == 0:
print(n, 'is divisible by 5')
else:
print(n, 'is not divisible by 5')
if-elif-else tests several conditions from the top. The first one that is True has its block run, and all the rest are skipped, even if they are True too. The final else (optional) runs only when none was True. elif is short for "else if".
Marks 82: the first test fails, the second passes, so grade B is set and the third test is never made.
Python · the flowchart as code
marks = int(input('Marks: '))
if marks >= 90:
grade = 'A'
elif marks >= 75:
grade = 'B'
elif marks >= 60:
grade = 'C'
else:
grade = 'D'
print('Grade', grade)
Output · the user types 82
Marks: 82
Grade B
Python · sort three numbers
a = int(input('a: '))
b = int(input('b: '))
c = int(input('c: '))
if a > b:
a, b = b, a
if b > c:
b, c = c, b
if a > b:
a, b = b, a
print('Sorted:', a, b, c)
Output · the user types 27, 9, 14
a: 27
b: 9
c: 14
Sorted: 9 14 27
The sorting program uses three separate ifs, not elif: each comparison must be made whether or not the one before swapped anything.
Order matters
In an if-elif chain, put the strictest condition first. Testing marks >= 33 before marks >= 90 gives every topper a D, because the first True condition wins. The board also asks you to spot a missing colon after if/elif/else, or else if written for elif.
FLOW.03 · Flow of Control
Loops
11-CS11-IP12-CS
A loop repeats a block of statements. Python has two: for, which runs once for each item of a sequence (a counting loop), and while, which runs as long as a condition is True (a conditional loop). Use for when you know how many times; use while when you repeat until something happens.
Before the Python: what every loop looks like in a flowchart. A loop is a decision whose Yes path leads back to the same decision. It has three parts: a set-up before it, a test that decides whether to go round again, and a body that repeats and must change something the test looks at. Here is the factorial loop; its Python program is in the Factorial block at the end of this topic, and the for and while blocks below each have their own flowchart.
For n = 5 the body runs 5 times (i = 1 to 5); when i becomes 6 the test fails and f = 120 is printed.
for variable in sequence: takes the items of the sequence one at a time, in order. Each time, the loop variable is given the next item and the indented body runs. The loop ends after the last item. The sequence can be a string, list, tuple, dictionary or a range().
The for loop does the test and the "next item" step for you; you write only the body.
Python · for over a string and a list
for ch in 'KV':
print(ch)
for x in [3, 6, 9]:
print(x * 2, end=' ')
for k in range(7, 14, 4):
print(k, '@')
for i in range(3):
print('Hello', i)
Output
7 @
11 @
Hello 0
Hello 1
Hello 2
All three arguments must be integers, and step cannot be 0. If start is already past stop in the direction of the step, the range is empty and the loop body never runs. Try any values in the range() lab.
while condition: tests the condition; if it is True the body runs, then the condition is tested again, and so on. When it becomes False the loop ends. If it is False the first time, the body never runs. Something in the body must change the condition, or the loop never stops (an infinite loop).
In a while loop you write the test and the update yourself. Leave out n += 1 and the test stays True for ever.
Python · count to 5
n = 1
while n <= 5:
print(n, end=' ')
n += 1
print()
print('After the loop n =', n)
Output
1 2 3 4 5
After the loop n = 6
Python · sum of digits
n = int(input('Number: '))
total = 0
while n > 0:
total += n % 10 # add the last digit
n //= 10 # drop the last digit
print('Sum of digits =', total)
An infinite loop is a loop whose condition never becomes False, so it runs for ever: the program seems to hang, or fills the screen with the same output. It is almost always a logical error (ERR.01): Python gives no message. To stop a runaway program, press Ctrl+C (in IDLE, or Shell → Interrupt Execution); Python stops it with a KeyboardInterrupt.
The body must change something the test looks at. Here nothing does, so every trip round the loop is exactly the same.
Python · the update is missing
n = 1
rounds = 0
while n <= 5: # n is never changed
print(n, end=' ')
rounds += 1
if rounds == 8: # safety stop, only for
break # this demonstration
print('| still', n, 'after', rounds, 'rounds')
Output · stopped by the safety break
1 1 1 1 1 1 1 1 | still 1 after 8 rounds
Python · fixed
n = 1
while n <= 5:
print(n, end=' ')
n += 1 # the update ends the loop
print('| n =', n)
Output
1 2 3 4 5 | n = 6
The safety break in the first program is only there so it can be run on this page; without it, it would print 1 for ever.
Common cause
Example
Fix
The update is missing
while n <= 5: with no n += 1
Change the loop variable in the body
The update goes the wrong way
while n <= 5: with n -= 1
Move towards the end condition
The update jumps over the end value
while n != 0: with n = 10 and n -= 3
Test with > or <, not !=
The update is outside the loop
n += 1 written without indentation, after the loop
Indent it into the loop's block
The condition can never be False
while True: with no break
Add a break that is sure to run
Python · stepping over the end value
n = 10
rounds = 0
while n != 0: # 7, 4, 1, -2 ... skips 0
n -= 3
rounds += 1
if rounds == 6: # safety stop
break
print('n =', n, 'after', rounds, 'rounds')
Output · stopped by the safety break
n = -8 after 6 rounds
An infinite loop can also be deliberate: while True: with a break inside is the usual way to repeat until the user says stop, when you can't know in advance how many times.
Python · while True with a way out
total = 0
while True: # on purpose: no end test
n = int(input('Number (0 to stop): '))
if n == 0:
break # the only way out
total += n
print('Total =', total)
Output · the user types 5, 12, 8, then 0
Number (0 to stop): 5
Number (0 to stop): 12
Number (0 to stop): 8
Number (0 to stop): 0
Total = 25
A for loop over a list or a range() can't run for ever: it stops after the last item.
break leaves the loop at once; the program goes on after the loop. continue skips the rest of this iteration only and goes on to the next one. Both act on the innermost loop they are in.
continue returns to the top of the loop; break goes past its end. A loop's else block (below) runs only on the bottom path, never after a break.
Python · break
for i in range(1, 10):
if i == 5:
break
print(i, end=' ')
print('| loop left at i =', i)
Output
1 2 3 4 | loop left at i = 5
Python · continue skips multiples of 3
for i in range(1, 8):
if i % 3 == 0:
continue
print(i, end=' ')
Output
1 2 4 5 7
A loop may have an else block. It runs when the loop ends normally, and is skipped when the loop is left by break. This suits searching: "if no divisor was found, the number is prime".
Python · prime or composite, with for-else
for n in [29, 91]:
for d in range(2, n):
if n % d == 0:
print(n, 'is composite, divisor', d)
break
else:
print(n, 'is prime')
A loop inside another loop is a nested loop. For each iteration of the outer loop, the inner loop runs completely. With 3 outer and 4 inner iterations, the inner body runs 3 × 4 = 12 times. Typically the inner loop prints one row with end=' ', and a print() after it (in the outer loop) moves to the next line.
Read it like a page: the outer loop moves down one row at a time; for each row the inner loop goes all the way across.
Python · a table, row by row
for i in range(1, 4):
for j in range(1, 5):
print(i * j, end=' ')
print()
Patterns are the classic nested-loop programs. The outer loop picks the row; the inner loop prints that row's items on one line; print() ends the row. Work out how many items row i has (i, or 6 − i …) and what each item is. chr(65) is 'A', chr(66) is 'B', and so on.
Pattern 1 · stars
for i in range(1, 6):
for j in range(i):
print('*', end='')
print()
*
**
***
****
*****
Pattern 2 · counting down
for i in range(5, 0, -1):
for j in range(1, i + 1):
print(j, end='')
print()
12345
1234
123
12
1
Pattern 3 · letters
for i in range(1, 6):
for j in range(i):
print(chr(65 + j), end='')
print()
To add up a series, start a total at 0 and add one term per iteration. Write the i-th term as an expression in i: in 1 + x + x² + … the term is x ** i; for alternating signs multiply by (-1) ** i; for a factorial in the denominator keep a running fact *= i instead of recomputing it.
Python · two series
x = int(input('x: '))
n = int(input('n: '))
s1 = s2 = 0
for i in range(n + 1):
s1 += x ** i # 1 + x + x^2 ...
s2 += (-1) ** i * x ** i # 1 - x + x^2 ...
print('1 + x + ... + x^n =', s1)
print('1 - x + ... x^n =', s2)
x, n = 2, 4
s3 = s4 = 0
fact = 1
for i in range(1, n + 1):
fact *= i # i!
s3 += x ** i / i # x + x^2/2 ...
s4 += x ** i / fact # x + x^2/2! ...
print('x + x^2/2 + ... =', round(s3, 4))
print('x + x^2/2! + ...=', round(s4, 4))
Output
x + x^2/2 + ... = 10.6667
x + x^2/2! + ...= 6.0
Check by hand: 1 + 2 + 4 + 8 + 16 = 31 and 1 − 2 + 4 − 8 + 16 = 11. For the last series: 2 + 4/2 + 8/6 + 16/24 = 2 + 2 + 1.333 + 0.667 = 6.
The factorial of n, written n!, is 1 × 2 × 3 × … × n, with 0! = 1. Start f at 1 (not 0, or every product is 0) and multiply it by each number from 1 to n. Factorials of negative numbers do not exist, so check first.
Python · factorial of a positive number
n = int(input('Enter a number: '))
if n < 0:
print('No factorial for a negative number')
else:
f = 1
for i in range(1, n + 1):
f *= i
print('Factorial of', n, 'is', f)
Output · the user types 6
Enter a number: 6
Factorial of 6 is 720
Exam tip
For loop outputs, make a trace table: one column per variable, one row per iteration, plus what is printed. Watch end= (no new line), the last value of range (stop − 1), and whether a print() is inside or outside the loop. "Difference between break and continue" and "for vs while" are frequent 2-mark questions.
Chapter practice · FLOW
Check your understanding
range() lab
Python shell · worked out as Python does
Predict the output
for k in range(7, 40, 6):
print(k, end='-')
7-13-19-25-31-37-
7, 13, 19, 25, 31, 37; the next, 43, is past 40. end='-' puts a dash after every value, the last one too.
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i, end=' ')
1 2 4 5
i is increased before the test, so 3 is skipped by continue but the loop still reaches 5.
L = [3, 10, 6, 13]
for I in L:
for J in range(I % 2, 5):
print(J, '#', end='')
print()
For odd I (3, 13) J starts at 1; for even I (10, 6) at 0. Each row ends at 4; print() starts a new line.
marks = 95
if marks >= 33:
print('D')
elif marks >= 90:
print('A')
else:
print('Fail')
D
95 >= 33 is True, so the first block runs and the elif is never tested.
for i in range(1, 6):
for j in range(1, i):
print(j % 2, end=' ')
print()
1
1 0
1 0 1
1 0 1 0
When i = 1, range(1, 1) is empty, so the first line is blank. Then j % 2 alternates 1, 0, 1, 0.
x = 10
while x > 0:
x -= 3
print(x, end=' ')
7 4 1 -2
x is reduced, then printed: 7, 4, 1, −2. Then x > 0 is False and the loop ends.
Self-check quiz
Which is the empty statement in Python?
pass does nothing; it fills a place where a statement is required.
Which statement gives iterative flow?
for and while repeat; if, elif and else select.
How many times does for i in range(2, 20, 4): run?
2, 6, 10, 14, 18: five values (22 is past 20).
list(range(5, 0, -1)) is:
Counting down, the stop value 0 is still left out.
In an if-elif-else chain, how many blocks can run?
The first True condition wins; with an else, exactly one runs.
What does continue do?
It jumps to the next iteration; break would end the loop.
"A break in an inner loop ends all the loops at once." This is:
break leaves only the innermost loop it is in.
To find a factorial, the product variable should start at:
Starting at 0 would make every product 0.
Which loop never ends?
i never changes, so i < 3 stays True: an infinite loop.
How many times does the body of while x < 10: run if x starts at 15?
The test is False the first time, so the body is skipped.
With for i in range(3): outside and for j in range(4): inside, the inner body runs:
The inner loop runs fully for each outer iteration: 3 × 4.
Your score
– / 11
Answer every question to see your score.
One-page revision
Statementsempty (pass) · simple · compound
3 flowssequential · conditional · iterative
if … :colon, then an indented block
if-elif-elsefirst True wins; the rest skipped
for x in seq:once per item
range(a, b, s)a, a+s, … before b; stop left out
range(5, 1)empty: the body never runs
while cond:repeats while True; update inside
Infinite looptest never False; stop with Ctrl+C
breakleave the loop now
continueskip to the next iteration
loop elseruns if no break happened
Nestedinner runs fully per outer turn
Factorialf = 1, f *= i for i in 1 … n
Chapter 8 of 19 · STR
Strings
Text in Python: how each character is reached by its index, how strings are joined, repeated, searched and sliced, how a loop walks through them, and the string methods the board asks about by name.
STR.01 · Strings
Introduction to Strings
11-CS12-CS
A string is a sequence of characters enclosed in quotes. Single '…' and double "…" quotes mean the same; use one kind when the text contains the other ("It's"). Triple quotes '''…''' or """…""" allow a string to run over several lines. Strings are immutable: no character can be changed in place (DTY.06).
Python · three ways to write a string
s1 = 'Hello'
s2 = "It's fine"
s3 = '''Line one
Line two'''
print(s1, s2)
print(s3)
print(len(s1), len(s3))
Output
Hello It's fine
Line one
Line two
5 17
The triple-quoted string has 17 characters: 8 + the newline + 8. A newline is one character.
Each character has a position, its index. Forward indexes count from 0 at the left to len(s) − 1. Backward (negative) indexes count from −1 at the right to −len(s). s[i] gives the character at index i as a string of length 1.
Each character has two indexes: s[1] and s[-5] are both 'Y'. Any index from −6 to 5 works; anything else is an IndexError.
Python shell
>>> s = 'PYTHON'
>>> s[0]
'P'
>>> s[5]
'N'
>>> s[-1]
'N'
>>> s[-6]
'P'
>>> s[len(s) - 1]
'N'
>>> s[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[0] = 'J'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Exam tip
The last character is s[-1] or s[len(s) - 1], never s[len(s)] (IndexError). s[0] = 'J' is a TypeError: to "change" a string, build a new one, e.g. s = 'J' + s[1:].
STR.02 · Strings
String Operations
11-CS12-CS
Four operations work on whole strings: + joins, * repeats, in searches and [a:b:c] slices. Each one gives a new string; the original is never changed.
Repetition with * repeats a string a whole number of times; the number can be on either side. Zero or a negative number gives the empty string '', not an error. A float is a TypeError.
Python shell
>>> 'ab' * 3
'ababab'
>>> 3 * '-'
'---'
>>> 'Smile' * 0
''
>>> 'Smile' * -2
''
>>> 'ab' * 2.5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
A slices[start:stop:step] picks out part of a string. It starts at index start, goes up to but not including stop, jumping step each time. Leave any part out to use its default: start = 0, stop = the end, step = 1. With a negative step the slice walks backwards, and the defaults become "from the last character" and "to the very start".
Top: think of start and stop as cuts between characters; the slice is what lies between the two cuts. Bottom: with a step, read characters from start, jumping step each time.
A slice never gives an IndexError: s[2:100] just stops at the end.
If start is not before stop in the direction of the step, the result is empty: s[6:2] is '', but s[6:2:-1] is 'ETUP'.
s[::-1] reverses the whole string; s[:] is a copy of all of it.
Exam tip
For s[a:b] the number of characters is b − a (when both are inside the string). For a negative start such as 'Soft Skills'[-3::-3], first turn it into a forward index: −3 + 11 = 8, then step back: 8, 5, 2 → 'lSf'. Try any slice in the slicing lab.
STR.03 · Strings
Traversing a String
11-CS12-CS
Traversing means visiting every character in turn, usually to count, test or rebuild. There are two ways: loop over the characters (for ch in s) when you only need each character, or over the indexes (for i in range(len(s))) when you also need its position or its neighbours. A while loop with an index works too.
Python · by character, then by index
s = 'Kabir'
for ch in s:
print(ch, end=' ')
print()
for i in range(len(s)):
print(i, s[i], end=' | ')
Output
K a b i r
0 K | 1 a | 2 b | 3 i | 4 r |
Python · reverse with while
s = 'Python'
rev = ''
i = len(s) - 1
while i >= 0:
rev += s[i]
i -= 1
print(rev)
Output
nohtyP
Counting kinds of characters
A practical-list program: count vowels, consonants, upper and lower case letters and digits. Each character is tested with string methods (STR.04) and in.
Python · count and classify
text = 'Hello World 2025'
v = c = up = lo = dg = 0
for ch in text:
if ch.isupper():
up += 1
elif ch.islower():
lo += 1
elif ch.isdigit():
dg += 1
if ch.isalpha():
if ch in 'aeiouAEIOU':
v += 1
else:
c += 1
print('Vowels', v, 'Consonants', c)
print('Upper', up, 'Lower', lo, 'Digits', dg)
Output
Vowels 3 Consonants 7
Upper 2 Lower 8 Digits 4
Building a new string
Since a string can't be changed, a traversal that "changes" characters starts with an empty string and adds the new character each time with +=. This is the pattern of most board output questions.
Python · rebuild character by character
s = 'kv no 2'
new = ''
for ch in s:
if ch.isalpha():
new += ch.upper()
elif ch == ' ':
new += '_'
else:
new += ch
print(new)
Output
KV_NO_2
Python · palindrome check
w = input('Word: ')
if w.lower() == w[::-1].lower():
print(w, 'is a palindrome')
else:
print(w, 'is not a palindrome')
Output · the user types Malayalam
Word: Malayalam
Malayalam is a palindrome
Exam tip
In character-by-character output questions, write a small table: character, which branch it takes (isdigit? isalpha? else), and what is added. Spaces and punctuation usually fall into the else branch. Check whether print is inside the loop (prints every step) or after it (prints once).
STR.04 · Strings
String Methods and Functions
11-CS12-CS
A method is a function that belongs to a type and is called on a value with a dot: s.upper(). len() is a built-in function instead: len(s). Because strings are immutable, every string method returns a new value and leaves s unchanged; to keep the result, assign it: s = s.upper().
>>> s = 'banana'
>>> s.index('n')
2
>>> s.index('x')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
Each is…() method returns True or False. One program tests eight strings with all six; an empty string gives False for every test.
Python · every test on every string
tests = ['Class12', 'Python', '2025', 'hello',
'KV NO. 1', ' ', 'a b', '']
head = 'alnum alpha digit lower upper space'
print('string'.ljust(11) + head)
for s in tests:
r = [s.isalnum(), s.isalpha(), s.isdigit(),
s.islower(), s.isupper(), s.isspace()]
line = repr(s).ljust(11)
for ok in r:
line += ('yes' if ok else '-').center(6)
print(line)
Splits at every sep into a list. With no sep, splits on runs of whitespace.
>>> 'a b c'.split()
['a', 'b', 'c']
>>> '2025-11-19'.split('-')
['2025', '11', '19']
>>> 'a,b,,c'.split(',')
['a', 'b', '', 'c']
>>> 'so many books so little time'.split('so')
['', ' many books ', ' little time']
Often confused
Difference
find() vs index()
Both give the first position; when sub is missing, find gives −1 and index raises ValueError
capitalize() vs title()
capitalize: only the first character of the whole string; title: the first letter of every word
partition() vs split()
partition: splits once, gives a 3-tuple that keeps sep; split: splits everywhere, gives a list without sep
split() vs split(' ')
No argument: any run of spaces counts as one, and no empty strings appear; ' ': every single space splits
Exam tip
Splitting on a separator that is at the start gives an empty string first: 'so many books so little time'.split('so') is ['', ' many books ', ' little time']. Count list items, not words: len('CBSE 2022-2023'.split('2')) is 6. Remember s.upper() alone changes nothing; write s = s.upper().
Chapter practice · STR
Check your understanding
Slicing lab
Predict the output
print('CS2025'[:-2])
s = 'Soft Skills'
print(s[-3::-3])
Msg = 'Wings of Fire!'
print(Msg[-9::2])
CS20
lSf
fFr!
'CS2025'[:-2] drops the last two. −3 in 'Soft Skills' is index 8: 8, 5, 2 → l S f. −9 in 'Wings of Fire!' (14 long) is index 5, a space: 5, 7, 9, 11, 13 → ' fFr!'.
code = 'Oh! Kolkata-25'
new = ''
for ch in code:
if ch.isdigit():
new = new + str(int(ch) + 1)
elif ch.isalpha():
new = new + ch.lower()
else:
new = new + '#'
print(new)
oh##kolkata#36
Letters become lower case, '!', ' ' and '-' become '#', and each digit goes up by 1: 2 → 3, 5 → 6.
text = 'We shall overcome some day'
print(text.partition('me'))
print(text.split('me'))
Both 'th's become 'j'. index() searches the original msg, which was not changed: B0 u1 i2 l3 d4 a5.
s = 'Random Only Memory'
s = ' ' + s
wrd = ''
for i in range(len(s)):
if s[i] == ' ':
wrd = wrd + s[i + 1]
print(wrd, wrd.count('R'))
ROM 1
The added leading space makes the first letter follow a space too, so every word's first letter is collected.
st = 'CBSE 2022-2023'
print(len(st.split('2')))
print(st.split('2'))
6
['CBSE ', '0', '', '-', '0', '3']
Five 2s make six pieces. Two 2s side by side ("22") leave an empty string between them.
Self-check quiz
For s = 'KENDRIYA', what is s[-3]?
−1 is A, −2 is Y, −3 is I.
'Python'[1:4] is:
Indexes 1, 2, 3; stop 4 is left out.
print('now-', 'Smile' * -2) shows:
A negative count gives '', so only 'now-' and a space are printed.
'TariffWar'.find('war') gives:
find is case-sensitive: 'war' is not in the string, so −1.
Which method returns a tuple?
partition gives (before, sep, after).
Which gives True?
Letters and digits only, not empty. '.' fails isdigit; 'A' fails islower; '' is never "space".
After s = 'kv'; s.upper(), s is:
upper() returns a new string; it was not assigned, so s is unchanged.
'*'.join('ABC') is:
A string is a sequence of characters; the separator goes only between them.
Your score
– / 8
Answer every question to see your score.
One-page revision
s[0] · s[-1]first · last character
s[a:b]a … b−1; b − a characters
s[::-1]reversed copy
Slice past the endno error; it just stops
+ · *join (str only) · repeat (int; ≤ 0 gives '')
insubstring test, case-sensitive
Immutables[0] = 'x' is a TypeError
find · index−1 · ValueError when missing
capitalize · titlefirst char only · every word
strip('*')removes * from both ends
partitiontuple of 3, at the first sep
split · joinstr → list · list of str → str
Chapter 9 of 19 · LST
Lists
The list is Python's all-purpose container: an ordered, changeable sequence of any values. This chapter covers making lists, reaching and changing items, the list operations and methods, and the three programs every student must be able to write: max/min/mean, linear search and frequency count.
LST.01 · Lists
Introduction to Lists
11-CS11-IP12-CS
A list is an ordered sequence of items, separated by commas, in square brackets: [10, 20, 30]. The items can be of any type, mixed, including other lists. Lists are mutable: items can be changed, added and removed after the list is made.
Write the items in brackets, start from an empty list [], convert another sequence with list(), or repeat a value with *. To fill a list from the user, start empty and append() each value in a loop.
List indexes work exactly like string indexes (STR.01): 0 to len − 1 from the left, −1 to −len from the right. Unlike a string, a list item can be assigned: L[2] = 99 changes the list in place.
Python shell
>>> L = [10, 20, 30, 40, 50]
>>> L[0], L[-1]
(10, 50)
>>> L[2] = 99
>>> L
[10, 20, 99, 40, 50]
>>> L[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
A nested list is a list whose items are lists, like a table of rows. M[i] is row i (a whole list) and M[i][j] is item j of that row. A nested loop visits every item.
The first index picks the row, the second picks the item in that row. len(M) counts rows (2); len(M[0]) counts the items in one row (3).
M = [[1, 2, 3], [4, 5, 6]]
for row in M:
for x in row:
print(x, end=' ')
print()
Output
1 2 3
4 5 6
Exam tip
For a list of strings, a second index goes into the string: with L = ['Kendriya', 'Vidyalaya', 'Sangathan'], L[1][0] is 'V' and L[2][-1] is 'n'.
LST.02 · Lists
List Operations
11-CS11-IP12-CS
Lists support the same four sequence operations as strings: +, *, in and slicing. +, * and slicing make new lists. Because lists are mutable, a slice can also appear on the left of = to replace part of a list.
L[start:stop:step] follows the same rules as string slicing (STR.02) and gives a new list. Assigning to a slice replaces those items, and the list can grow or shrink.
b = a does not copy: both names share one list (DTY.06). To get an independent copy use a[:], list(a) or a.copy().
Python · alias or copy?
a = [1, 2, 3]
b = a # a second name, same list
c = a[:] # a new list: a copy
a[0] = 99
print(a, b, c)
print(a is b, a is c)
Output
[99, 2, 3] [99, 2, 3] [1, 2, 3]
True False
Exam tip
a = a + [3] makes a new list, but a += [3] changes the list in place, so every alias of a sees the change. Watch for this in output questions that use b = a.
LST.03 · Lists
Traversing a List
11-CS11-IP12-CS
To traverse a list is to visit each item in turn. for x in L gives the items; for i in range(len(L)) gives the indexes, and is needed whenever you want to change items, or compare an item with its neighbour.
Python · by item and by index
marks = [78, 91, 65]
for m in marks:
print(m, end=' ')
print()
for i in range(len(marks)):
print('Student', i + 1, ':', marks[i])
L = [1, 2, 3]
for x in L:
x = x * 10 # changes x, not L
print(L)
for i in range(len(L)):
L[i] = L[i] * 10 # changes L itself
print(L)
Output
[1, 2, 3]
[10, 20, 30]
In the first loop, x is just a name for each item; giving x a new value does not touch the list. The second loop assigns to L[i], which does.
Python · swap items at even and odd places
L = [10, 20, 30, 40, 50, 60]
for i in range(0, len(L) - 1, 2):
L[i], L[i + 1] = L[i + 1], L[i]
print(L)
Output
[20, 10, 40, 30, 60, 50]
Common mistake
Never add or remove items from a list while a for loop is going through it. In for i in lst: lst.remove(i) on [1, 2, 3, 4], removing 1 shifts 2 into index 0, so the loop's next look (index 1) finds 3 and skips 2. The result is [2, 4], not [].
Python · the board question, run
lst = [1, 2, 3, 4]
for i in lst:
lst.remove(i)
print(lst)
[2, 4]
LST.04 · Lists
List Methods and Functions
11-CS11-IP12-CS
Unlike string methods, most list methods change the list in place and return None: append, extend, insert, remove, reverse, sort. Only pop, count and index give back a value. The built-in functions len, list, sorted, min, max and sum never change the list.
Making and measuring
list() turns any sequence into a list, one item per element; len() counts the items at the top level only.
>>> L = [10, 20, 30, 20]
>>> L.index(20)
1
>>> L.index(99)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 99 is not in list
Removing items
remove() is told what to delete; pop() is told where. Only pop() gives the deleted item back.
Deletes the first item equal to x (by value). ValueError if absent.
>>> L = [5, 3, 5, 8]
>>> L.remove(5)
>>> L
[3, 5, 8]
>>> L.remove(9)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
Removes and returns the item at index i (by position); the last if i is left out.
>>> L = [10, 20, 30, 40]
>>> L.pop()
40
>>> L.pop(0)
10
>>> L
[20, 30]
>>> [].pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop from empty list
Putting in order
reverse() and sort() rearrange the list itself and return None; sorted() leaves it alone and returns a new, sorted list.
>>> sum([4, 9, 2])
15
>>> sum([1.5, 2])
3.5
>>> sum(['a', 'b'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Often confused
Difference
append() vs extend()
append adds its argument as one item; extend adds each item of it
remove(x) vs pop(i)
remove deletes by value and returns None; pop deletes by index and returns the item
sort() vs sorted()
sort changes the list and returns None; sorted returns a new list and works on any sequence
L.reverse() vs L[::-1]
reverse changes L; the slice gives a reversed copy
Exam tip
L = L.sort() leaves L as None, and print(L.append(5)) prints None. "Differentiate append and extend / remove and pop / sort and sorted" are standard 2-markers: give one example each.
LST.05 · Lists
List Programs
11-CS11-IP12-CS
The syllabus names three programs on a list of numbers. Each one is a single traversal; write them both ways: with your own loop (what the examiner wants to see) and with built-ins (to check your answer).
Start both the largest and smallest at the first item (not at 0, which fails for all-negative lists), then compare every item. Keep a running total for the mean.
Python · one pass
L = [45, 12, 78, 34, 89, 23]
big = small = L[0]
total = 0
for x in L:
if x > big:
big = x
if x < small:
small = x
total += x
print('Max', big, 'Min', small)
print('Mean', total / len(L))
print('Check:', max(L), min(L), sum(L) / len(L))
Output
Max 89 Min 12
Mean 46.833333333333336
Check: 89 12 46.833333333333336
Linear search checks the items one by one, from the start, until it finds the key or reaches the end. It works on unsorted lists. In the worst case (key last, or absent) it makes n comparisons. A for-else prints "not found" only when the loop ended without break.
The search stops at the first match; 89 and 23 are never looked at. Searching for 50 would compare all six and report "not found".
Python · linear search with for-else
L = [45, 12, 78, 34, 89, 23]
key = int(input('Search for: '))
for i in range(len(L)):
if L[i] == key:
print(key, 'found at index', i)
break
else:
print(key, 'not found')
The frequency of a value is how many times it occurs. For one value, count with a loop (or L.count(x)). For every value, go through the list and report each value only the first time you meet it, keeping a list of values already seen. A dictionary does this more neatly (DICT.05).
Python · one value, by hand
L = [2, 5, 2, 8, 5, 2]
key = 2
c = 0
for x in L:
if x == key:
c += 1
print(key, 'occurs', c, 'times')
Output
2 occurs 3 times
Python · every value
L = [2, 5, 2, 8, 5, 2]
seen = []
for x in L:
if x not in seen:
print(x, 'occurs', L.count(x), 'times')
seen.append(x)
Output
2 occurs 3 times
5 occurs 2 times
8 occurs 1 times
Exam tip
When asked to "write a program", don't just call max(L): show the loop, and initialise from L[0]. For search, print "not found" only after the whole list has been checked, never in an else inside the loop (that prints it for every non-matching item).
3 goes in at index 2 and extend adds 8 and 5. append returns None, but P still gets [2, 3] as its 8th item. P[::2] takes indexes 0, 2, 4, 6: 1, 3, 6, 5.
cities = ['Delhi', 'Kolkata', 'Chennai',
'Mumbai', 'Pune', 'Agra']
result = []
for city in cities:
if len(city) % 2 == 0:
result.append(city[-2:].upper())
print(result)
['AI', 'NE', 'RA']
Even lengths: Mumbai (6), Pune (4), Agra (4). Their last two letters, in capitals.
L = ['Kendriya', 'Vidyalaya', 'Sangathan']
print(L[1][0] + 2 * L[2][-1])
Vnn
'V' + 2 × 'n'. * comes before +.
nums = [81, 82, 18, 48, 99, 60, 25]
for i in range(4):
if nums[i] % 3 == 0:
nums[i] %= 4
if nums[i] % 2 == 0:
nums[i] *= 2
for e in nums:
print(e, end='#')
1#164#4#0#99#60#25#
Only the first four change. 81 → 81 % 4 = 1 (odd, stays). 82 is even → 164. 18 → 2 → 4. 48 → 0 → 0.
lst = [1, 2, 3, 4]
for i in lst:
lst.remove(i)
print(lst)
[2, 4]
Removing shifts the items left, so the loop skips every second one (LST.03).
a = [1, 2]
b = a
c = a[:]
a += [3]
print(b, c)
[1, 2, 3] [1, 2]
b is the same list as a, and += changes it in place. c is a separate copy made before.
Self-check quiz
For L = [10, 20, 30, 40], L[-3:] is:
From index −3 (20) to the end.
After L = [1, 2]; L.append([3, 4]), len(L) is:
append adds the list [3, 4] as a single item.
Which removes an item by its index and returns it?
pop(i) returns the removed item; remove(x) works by value.
L = [3, 1, 2]; print(L.sort()) shows:
sort() changes L and returns None.
[1, 2] * 2 + [3] is:
* repeats first, then + joins.
For M = [[1, 2], [3, 4], [5, 6]], M[2][0] is:
Row 2 is [5, 6]; its item 0 is 5.
L = ['a', 'b']; L.insert(0, 'z') gives:
insert puts the item before index 0, at the front.
In linear search on a list of n items, the most comparisons needed is:
If the key is last or missing, every item is checked.
Which makes an independent copy of list a?
A full slice builds a new list; b = a only adds a second name.
sum([2, 4, 6]) / len([2, 4, 6]) is:
12 / 3 with / gives a float.
Your score
– / 10
Answer every question to see your score.
One-page revision
[ ] · list()make a list; mutable, mixed types
L[i] = xchange one item in place
M[i][j]row i, then item j
+ · * · injoin · repeat · equals an item?
b = a · a[:]same list · a copy
append · extendone item · each item
insert(i, x)x goes before index i
remove · popby value (None) · by index (returns it)
sort · sortedin place, None · new list
count · indexhow many · first position
min · max · sumsmallest · largest · total
Searchloop + break; for-else for "not found"
Chapter 10 of 19 · TUP
Tuples
A tuple is a list that can't be changed. Everything about reading a list carries over; anything that would change it is not allowed. Tuples are used for fixed records, for returning several values at once, and for swapping values in one line.
TUP.01 · Tuples
Introduction to Tuples
11-CS12-CS
A tuple is an ordered, immutable sequence of items of any types, written with commas, usually in round brackets: (10, 20, 30). It is the comma that makes a tuple, not the brackets: 1, 2, 3 is a tuple too, and a one-item tuple needs a trailing comma, (5,); (5) is just the int 5 in brackets.
In tuple assignment several names on the left of = receive the items of a tuple on the right, in order. Writing values with commas packs them into a tuple; giving a tuple to several names unpacks it. The right side is worked out completely first, which is why x, y = y, x swaps two values with no temporary variable.
Unpacking matches by position. In x, y = y, x, the right side packs (9, 5) first, then unpacks it into x and y.
Python shell
>>> a, b, c = (10, 20, 30)
>>> print(a, b, c)
10 20 30
>>> x, y = 5, 9
>>> x, y = y, x
>>> print(x, y)
9 5
>>> p, q = (1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
List
Tuple
Brackets
[1, 2]
(1, 2), or just 1, 2
Mutable?
Yes: items can change
No: fixed once made
Methods
Many (append, sort, pop …)
Only count() and index()
Dictionary key?
No
Yes (if its items are immutable)
Use for
Data that grows or changes
Fixed records; returning many values
Exam tip
type((5)) is int, type((5,)) is tuple. "Which statement is incorrect for tup = (55, 100, 200, 25)?" The one that assigns: tup[0] = 50. "How is a list different from a tuple?" Mutability, brackets and one use of each.
TUP.02 · Tuples
Tuple Operations
11-CS12-CS
Tuples support +, *, in and slicing, exactly as lists do. Each gives a new tuple. There is no slice assignment, because the tuple can't change.
t1 + t2 joins two tuples into a new one. To add one value, make it a one-item tuple: t + (4,). t += (4,) also builds a new tuple and moves the name t to it; any other name for the old tuple still sees the old one.
Python shell
>>> (1, 2) + (3,)
(1, 2, 3)
>>> (1, 2) + 3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "int") to tuple
Python · a board question
tuple1 = (1, 2, 3)
tuple2 = tuple1
tuple1 += (4,) # makes a NEW tuple
print(tuple1, tuple2)
print(tuple1 == tuple2)
t * n repeats the items n times. Note the brackets in the last line: [tup] * 3 repeats a list holding the tuple, so the result is a list of three tuples.
t[start:stop:step] gives a new tuple, with the string rules (STR.02). With the default step of +1, a start to the right of the stop gives the empty tuple ().
tup1[-2:-5] is (): −2 is to the right of −5 and the step is +1. To count backwards you need [-2:-5:-1], which gives (80, 70, 60).
TUP.03 · Tuples
Tuple Methods and Functions
11-CS12-CS
A tuple has only two methods, count() and index(), because every other list method would change it. The built-in functions len, tuple, sorted, min, max and sum work as for lists.
Python shell · a tuple has no append()
>>> (1, 2, 3, 4).append(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
Making and measuring
tuple() turns any sequence into a tuple; len() counts the items at the top level only.
>>> t = (1, 2, 1, 1)
>>> t.index(2)
1
>>> t.index(9)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple
Putting in order
A tuple can't be sorted in place, so there is no t.sort(). sorted() reads it and returns a new list.
Assertion: "(1, 2, 3, 4).append(5) modifies the tuple." False: tuples have no append, so it is an AttributeError. The Reason "append() adds to the end of a list in place" is true, but about lists. sorted(t) gives square brackets in the output.
TUP.04 · Tuples
Tuple Programs
11-CS12-CS
The three list programs (LST.05) work on tuples unchanged, as long as they only read the items. The one difference is building the tuple from input: since it can't grow, each new value makes a new tuple with t = t + (value,).
n = int(input('How many? '))
t = ()
for i in range(n):
t = t + (int(input('Value: ')),)
print(t)
print('Max', max(t), 'Min', min(t))
print('Mean', sum(t) / len(t))
Output · the user types 4, then 15, 8, 23, 4
How many? 4
Value: 15
Value: 8
Value: 23
Value: 4
(15, 8, 23, 4)
Max 23 Min 4
Mean 12.5
This version records the position in pos, starting from −1 to mean "not found yet", and decides after the loop. The last line checks it with in and index().
Python · search with a flag
t = (45, 12, 78, 34, 89, 23)
key = 89
pos = -1
for i in range(len(t)):
if t[i] == key:
pos = i
break
if pos == -1:
print(key, 'not found')
else:
print(key, 'found at index', pos)
print(key in t, t.index(key)) # the short way
To report each value once, check whether index i is the value's first position: t.index(t[i]) == i.
Python · count every value once
t = ('a', 'b', 'a', 'c', 'b', 'a')
for i in range(len(t)):
if t.index(t[i]) == i: # first time seen
print(t[i], 'occurs', t.count(t[i]))
Output
a occurs 3
b occurs 2
c occurs 1
Common mistake
t = t + (value) without the comma tries to add an int to a tuple: TypeError. A program that tries t[i] = … or t.append(…) must convert first: L = list(t), change L, then t = tuple(L).
With step +1, start −2 is already past stop −5, so the slice is empty. −5 to −2 is indexes 4, 5, 6.
t = (5)
u = (5,)
print(t * 2, u * 2)
10 (5, 5)
(5) is the int 5, so 5 × 2 = 10. (5,) is a tuple, so * repeats it.
tup = (5,)
result = [tup] * 3
print(result)
[(5,), (5,), (5,)]
[tup] is a list with one item, the tuple; repeating it gives a list of three tuples.
t = (1, 2, 3)
a, b, c = t
print(a + c, b * 2, t[::-1])
4 4 (3, 2, 1)
a = 1, b = 2, c = 3: 1 + 3 = 4, 2 × 2 = 4; the slice reverses the tuple.
Self-check quiz
Which of these is a tuple?
A one-item tuple needs the trailing comma.
For t = (4, 8, 12), which statement raises an error?
Item assignment is not allowed; making a new tuple is fine.
How many methods does a tuple have (besides the built-in functions)?
count() and index().
sorted((5, 2, 9)) returns:
sorted always returns a list.
After a, b = 3, 7 and a, b = b, a + b, the values are:
The right side (7, 3 + 7) is worked out first, then unpacked.
x, y = (1, 2, 3) gives:
Three items can't be unpacked into two names.
(1, 2) * 2 + (3,) is:
Repeat, then join.
Your score
– / 7
Answer every question to see your score.
One-page revision
(1, 2, 3)ordered, immutable, any types
(5,) · (5)a tuple · just the int 5
t[i] = xTypeError: can't change
a, b = 1, 2pack, then unpack by position
x, y = y, xswap in one line
t += (4,)a new tuple; aliases see the old
t[-2:-5](): start past stop with step +1
count · indexthe only two methods
sorted(t)returns a list
t + (v,)grow a tuple: make a new one
Chapter 11 of 19 · DICT
Dictionary
A dictionary stores values under names of your choosing, its keys, so you look a value up directly by its key instead of by position. Marks by student name, capitals by state, salaries by employee: whenever data comes in pairs, use a dictionary.
DICT.01 · Dictionary
Introduction to Dictionary
11-CS11-IP12-CS
A dictionary (dict) is a mutable collection of key: value pairs in curly braces: {'Asha': 91, 'Ravi': 78}. It is a mapping, not a sequence: items are found by key, and there are no positions 0, 1, 2. Since Python 3.7 a dictionary remembers the order in which keys were added.
Each item is a key and its value, joined by a colon. Keys must be unique and immutable (str, int, float, tuple); a list can't be a key. Values can be anything and may repeat. If the same key is written twice, the last value wins.
A lookup goes straight to the key, however large the dictionary. A key that is not there raises KeyError.
Write the pairs in braces, start from the empty dictionary {}, or use dict() with name=value arguments or a list of (key, value) pairs. To fill one from the user, start empty and assign d[key] = value in a loop.
d[key] gives the value stored under key, or a KeyError if the key is absent. d.get(key) gives None instead of an error, and d.get(key, default) gives the default. A number in brackets is a key too: marks[0] looks for the key 0.
Python shell
>>> marks = {'Asha': 91, 'Ravi': 78}
>>> marks['Ravi']
78
>>> marks['Meena']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'Meena'
>>> print(marks.get('Meena'))
None
>>> marks.get('Meena', 0)
0
>>> marks[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0
Exam tip
For {'Kerala': 3, …, 'Kerala': 1} the answer is the dictionary with Kerala once, value 1, in its first place, not an error. "Can a list be a key?" No: keys must be immutable (TypeError: unhashable type).
DICT.02 · Dictionary
Mutability of a Dictionary
11-CS11-IP12-CS
A dictionary is mutable: pairs can be added, changed and removed in place. The same statement, d[key] = value, either adds or modifies, depending on whether the key is already there.
del d[key] removes a pair; d.pop(key) removes it and returns its value. Both raise KeyError for a missing key.
Python shell
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> del d['a']
>>> d
{'b': 2, 'c': 3}
>>> d.pop('b')
2
>>> d
{'c': 3}
>>> del d['z']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'z'
Exam tip
Trace dictionary changes one statement at a time and write the dictionary after each. When a deleted key is assigned again, it comes back at the end: deleting 1 and re-adding it moves it after 3.
DICT.03 · Dictionary
Traversing a Dictionary
11-CS11-IP12-CS
A for loop over a dictionary gives its keys, in order; use d[key] for the value. To get both at once, loop over d.items() with two names; for values only, loop over d.values().
Python · keys, then pairs
marks = {'Asha': 91, 'Ravi': 78, 'Meena': 85}
for name in marks:
print(name, marks[name])
for name, m in marks.items():
if m > 80:
print(name, 'scored above 80')
marks = {'Asha': 91, 'Ravi': 78, 'Meena': 85}
for m in marks.values():
print(m, end=' ')
print()
print(list(marks.keys()))
Output
91 78 85
['Asha', 'Ravi', 'Meena']
A practical-list program: a dictionary of roll number → [name, marks]; show the students with marks above 75.
Python · values that are lists
students = {101: ['Asha', 91], 102: ['Ravi', 72],
103: ['Meena', 85]}
for roll in students:
name, mark = students[roll]
if mark > 75:
print(roll, name, mark)
Output
101 Asha 91
103 Meena 85
Common mistake
for x in d: gives keys, not values, so sum of x or x > 80 tests the wrong thing. Don't add or delete keys while looping over the same dictionary: Python stops with "dictionary changed size during iteration".
DICT.04 · Dictionary
Dictionary Methods and Functions
11-CS11-IP12-CS
Class XI IP needs len dict keys values items update del clear. Class XI and XII CS add get fromkeys copy pop popitem setdefault and the functions max min sorted. The functions work on the keys unless you pass d.values() or d.items().
Making and measuring
Three ways to build a dictionary; len() counts key: value pairs, not keys and values separately.
A statement, not a method: removes one pair, or the whole dictionary.
>>> d = {'a': 1, 'b': 2}
>>> del d['a']
>>> d
{'b': 2}
>>> del d
>>> d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
Missing key: d[k] raises KeyError; get returns None or the default
del d[k] vs d.pop(k)
Both remove; pop also returns the value and can take a default
clear() vs del d
clear leaves an empty dictionary; del d removes the name (then NameError)
update() vs setdefault()
update overwrites existing keys; setdefault never changes an existing key
Exam tip
max(d) compares keys: with names as keys it gives the alphabetically last name, not the topper. d.items() prints as dict_items([...]); wrap it in list() to get a plain list.
DICT.05 · Dictionary
Dictionary Programs
11-CS12-CS
Two suggested programs. Both build a dictionary in a loop, then read it back.
Count how many times each character appears in a string. Each character is a key and its count is the value: if the key is new, set it to 1; otherwise add 1. get(ch, 0) + 1 does both in one line.
Python · count with a dictionary
text = 'mississippi'
freq = {}
for ch in text:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1
print(freq)
# the same with get(): 0 when not yet seen
freq2 = {}
for ch in text:
freq2[ch] = freq2.get(ch, 0) + 1
print(freq2 == freq)
Create a dictionary of employees' names and salaries, show them, and look one up. get() with a default avoids a KeyError for a name that is not there.
Python · names and salaries
emp = {}
n = int(input('Employees: '))
for i in range(n):
name = input('Name: ')
emp[name] = int(input('Salary: '))
for name in emp:
print(name, emp[name], sep='\t')
who = input('Whose salary? ')
print(who, 'earns', emp.get(who, 'not found'))
The counting pattern (new key → 1, old key → +1) also counts words (for w in text.split():) and vowels. Function-based versions of these programs (def update_score(scores, name, new) …) are asked in Class XII.
Chapter practice · DICT
Check your understanding
Predict the output
test = {1: 'A', 2: 'B', 3: 'C'}
del test[1]
test[1] = 'D'
del test[2]
print(len(test), test)
2 {3: 'C', 1: 'D'}
After del 1: {2, 3}. Re-adding 1 puts it at the end: {2, 3, 1}. del 2 leaves two pairs.
data = {'Jan': 4300, 'Feb': 2800,
'Mar': 5600, 'Apr': 4000}
high = []
for month, sale in data.items():
if sale > 4100:
high.append(month)
print(sorted(high, reverse=True))
['Mar', 'Jan']
Jan (4300) and Mar (5600) are above 4100. Sorted in reverse: 'Mar' before 'Jan'.
d = {'x': '123', 'y': '456'}
res = ''
for k in d:
res += d[k].isdigit() * 5
print(res)
Traceback (most recent call last):
File "main.py", line 4, in <module>
res += d[k].isdigit() * 5
TypeError: can only concatenate str (not "int") to str
isdigit() * 5 is True * 5 = 5, an int; adding an int to the string res is a TypeError.
d = {'a': 1, 'b': 2}
print(d.get('c', 'Missing'), d.get('a', 'No'))
Missing 1
'c' is absent, so the default; 'a' is present, so its value.
d = {'apple': 15, 'banana': 7, 'cherry': 9}
s = ''
for key in d:
s = s + str(d[key]) + '@'
print(s[:-1])
15@7@9
The loop gives keys in order; [:-1] drops the last '@'.
Self-check quiz
Which can NOT be a dictionary key?
Keys must be immutable; a list is mutable.
For d = {'a': 1}, d['b'] gives:
Square brackets with a missing key raise KeyError; get() would give None.
d = {'x': 5}; d['x'] = 7; d['y'] = 9. Now d is:
An existing key is modified; a new key is added.
A for loop over a dictionary gives its:
Use .items() for pairs, .values() for values.
Which removes every item but keeps the dictionary?
clear() empties it; del d deletes the name itself.
dict.fromkeys(['a', 'b'], 0) is:
Each key gets the given value.
For d = {'Asha': 91, 'Ravi': 78}, max(d) is:
max compares keys: 'Ravi' > 'Asha' alphabetically.
d = {'a': 1}; d.setdefault('a', 5) returns:
The key exists, so its value is returned and nothing changes.
len({1: 'a', 2: 'b', 1: 'c'}) is:
The repeated key 1 is stored once (with 'c').
Your score
– / 9
Answer every question to see your score.
One-page revision
{k: v}mutable mapping; unique immutable keys
Same key twicelast value wins, first position
d[k]value, or KeyError
d.get(k, x)value, or x (None by default)
d[k] = vadds a new key, or changes an old one
del d[k] · pop(k)remove · remove and return
for k in dkeys; items() for pairs
keys values itemsviews; wrap in list() to print
update(d2)merge; d2's values win
popitem()last added pair, as a tuple
max · min · sortedwork on keys
Countd[x] = d.get(x, 0) + 1
Chapter 12 of 19 · MOD
Python Modules
A module is a file of ready-made functions and values that your program can borrow. The syllabus uses three from Python's standard library: math for calculations, random for chance, and statistics for averages. "What are the possible outputs?" questions on random appear in almost every paper.
MOD.01 · Python Modules
Importing Modules
11-CS12-CS
A module is a Python file (.py) containing functions, constants and other definitions. A module must be imported before its contents can be used. There are two ways, and they differ in which name your program gets.
With import math every use needs the prefix math.; with from math import sqrt you call sqrt() directly, but only the names you imported exist.
import math loads the module and creates one name, math. Use its contents with a dot: math.sqrt(16). import math as m gives the module a shorter name (an alias), so you write m.pi. Several modules can be imported in one line: import math, random.
Python shell
>>> import math
>>> math.sqrt(16)
4.0
>>> sqrt(16)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sqrt' is not defined
>>> import math as m
>>> m.pi
3.141592653589793
from math import sqrt, pi brings in just those names, to be used without the prefix. from math import * brings in every name, which is short but risky: a module's name can silently replace one of yours.
Python shell
>>> from math import sqrt, pi
>>> sqrt(49)
7.0
>>> pi
3.141592653589793
>>> math.floor(2.5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined. Did you forget to import 'math'?
Python · area and circumference
import math
r = float(input('Radius: '))
print('Area =', round(math.pi * r ** 2, 2))
print('Perimeter =', round(2 * math.pi * r, 2))
Output · the user types 7
Radius: 7
Area = 153.94
Perimeter = 43.98
Exam tip
"Which module must be imported to run this code?" Look for the prefix or the function: sqrt, ceil → math; randint → random; mean, mode → statistics. After import math, calling sqrt(16) alone is a NameError.
MOD.02 · Python Modules
math Module
11-CS12-CS
The math module has mathematical constants and functions. Most of its functions return a float; ceil() and floor() return an int. The trigonometric functions take angles in radians, not degrees (π radians = 180°).
math.ceil(-2.5) is −2 and math.floor(-2.5) is −3: with negatives, "up" is towards zero. math.sqrt(16) is 4.0, math.pow(2, 3) is 8.0 and math.fabs(-7) is 7.0: write the .0.
MOD.03 · Python Modules
random Module
11-CS12-CS
The random module produces pseudo-random numbers: each run of the program can give different values. The outputs below are one possible run; yours will differ. What matters for the exam is the range of values each function can give.
random.randrange() picks one value from what range() with the same arguments would give: stop is never included. randrange(10) is 0–9; randrange(1, 10, 2) is one of 1, 3, 5, 7, 9. If that range is empty, it is a ValueError.
Python shell · one possible run
>>> import random
>>> random.randrange(10)
9
>>> random.randrange(1, 10)
5
>>> random.randrange(1, 10, 2)
5
>>> random.randrange(5, 5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: empty range in randrange(5, 5)
Call
Possible values
Count
random()
0.0 ≤ x < 1.0 (a float)
—
randint(1, 5)
1, 2, 3, 4, 5
5
randrange(1, 5)
1, 2, 3, 4
4
randrange(5)
0, 1, 2, 3, 4
5
randrange(0, 10, 3)
0, 3, 6, 9
4
A board question: possible outputs
"What possible output(s) are expected? Also give the minimum and maximum values of start and end." Work it out in three steps: list each variable's possible values, list the outputs they can make, then test each option against that list.
Python · the question, run once
import random
nums = [5, 15, 25, 35, 45]
start = random.randint(1, 2)
end = random.randint(2, 4)
for i in range(start, end + 1):
print(nums[i], end='#')
Output · one possible run
15#25#35#
Python · every case, by trying them all
nums = [5, 15, 25, 35, 45]
for start in range(1, 3): # randint(1, 2)
for end in range(2, 5): # randint(2, 4)
out = ''
for i in range(start, end + 1):
out += str(nums[i]) + '#'
print(start, end, out)
start is at least 1, so nums[0] = 5 is never printed
(b) 15#35#
✗ No
The loop prints consecutive items; it can't skip 25
(c) 15#25#35#45#
✓ Yes
start = 1, end = 4
(d) 35#45#
✗ No
The first item printed is 15 or 25
start: minimum 1, maximum 2. end: minimum 2, maximum 4. The full table of six cases above is exactly what an examiner expects you to imagine.
Exam tip
randint includes both ends; randrange leaves out stop. When a list is indexed by a random value, the smallest and largest index tell you which items can never appear. Write the minimum and maximum of each variable first, then test the options one by one.
MOD.04 · Python Modules
statistics Module
11-CS12-CS
The statistics module finds averages of a list (or tuple) of numbers. It is often imported with an alias: import statistics as st.
Sort before finding the median by hand: [7, 1, 5, 3] → [1, 3, 5, 7], middle pair 3 and 5, median 4.0. For mode, count each value: in [10, 20, 10, 30, 10, 20, 30], 10 occurs three times, so the answer is 10.
Chapter practice · MOD
Check your understanding
random lab: every possible value
Every possible value
10 runs · yours will differ
Predict the output
import math
print(math.ceil(-2.5), math.floor(-2.5))
print(math.fabs(-3), abs(-3))
-2 -3
3.0 3
ceil goes up (towards +∞) to −2; floor goes down to −3. fabs gives a float, abs keeps the int.
import math
print(math.pow(2, 3), 2 ** 3, math.sqrt(16))
8.0 8 4.0
math.pow and math.sqrt return floats; ** on two ints gives an int.
import statistics as st
data = [4, 8, 8, 2, 8, 4]
print(st.mode(data), st.median(data))
print(st.mean(data))
colors = ['Red', 'Blue', 'Green'] for i in range(2, 5): j = random.randrange(5 - i) print(colors[j], end=' ') Which are possible? (a) Green Red Green (b) Red Red Red (c) Blue Blue Red (d) Green Green Red
(b) and (c).i = 2: randrange(3) → 0–2, any colour. i = 3: randrange(2) → 0–1, Red or Blue. i = 4: randrange(1) → always 0, Red. So the third word is always Red and the second is never Green.
Sub = ['Math', 'Phy', 'Chem', 'Bio'] for i in range(3, 0, -1): j = random.randint(0, i) When i is 3, what are the minimum and maximum values of j?
Minimum 0, maximum 3.randint includes both ends, so randint(0, 3) can give 0, 1, 2 or 3.
Self-check quiz
After from math import sqrt, which call works?
from-import gives the name sqrt directly; math itself is not defined.
math.floor(-7.2) is:
floor goes down, towards −∞, and returns an int.
Which can give 10?
Only randint includes its upper end; random() is always below 1.
math.pow(3, 2) returns:
math.pow always returns a float.
With a = random.randint(3, 5) and b = random.randint(2, 3), the minimum and maximum of a + b are:
Smallest 3 + 2 = 5; largest 5 + 3 = 8.
statistics.median([4, 1, 3, 2]) is:
Sorted 1 2 3 4: the mean of 2 and 3.
Which module has mode()?
mean, median and mode are in statistics.
"randrange(1, 5) gives 1 to 4 only, while randint(1, 5) gives 1 to 5." This is:
randrange leaves out stop; randint includes b.
Your score
– / 8
Answer every question to see your score.
One-page revision
import mathuse as math.sqrt(16)
from math import sqrtuse as sqrt(16); no math.
import math as man alias: m.pi
sqrt · pow · fabsalways return floats
ceil · floorup · down, as ints; ceil(-2.5) = −2
sin cos tanangles in radians
random()0.0 ≤ x < 1.0
randint(a, b)a … b, both included
randrange(a, b, s)like range(): b left out
mean · median · modeaverage · middle · most frequent
Chapter 13 of 19 · FUNC
Functions
A function is a named block of code that does one job, written once and called whenever it is needed. This chapter is where Class XII begins: how to define functions, pass them values, get results back, and which variables a function can see.
FUNC.01 · Functions
Types of Functions
12-CS
A function is a named, reusable block of statements that performs a task. It may take inputs (arguments) and may give back a result (its return value). Functions avoid repeating code, split a big program into small parts (decomposition, PSV.03), and make programs easier to read, test and change. Python's functions fall into three groups.
"Give an example of each type": len() is built-in, math.sqrt() is from a module, and any function you write with def is user-defined.
FUNC.02 · Functions
Creating User Defined Functions
12-CS
A function is defined with the keyword def, its name, its parameters in brackets and a colon; the indented lines below form its body. Defining a function only stores it. Nothing in the body runs until the function is called by writing its name with brackets.
The parameters p, r, t are names in the definition; the arguments 5000, 8, 2 are the values given in the call. The call is replaced by whatever the function returns.
Python · define once, call twice
def greet(name):
"""Print a welcome message."""
print('Welcome,', name)
greet('Asha')
greet('Ravi')
Output
Welcome, Asha
Welcome, Ravi
Function names follow the identifier rules (PYB.05). Use a verb that says what it does: greet, count_vowels.
The function must be defined before it is called; Python reads the file from the top.
A string just under the header is a docstring: it documents the function and is not printed.
Python · called before it is defined
print(area(5))
def area(r):
return 3.14 * r * r
Output
Traceback (most recent call last):
File "main.py", line 1, in <module>
print(area(5))
NameError: name 'area' is not defined
Exam tip
In "rewrite after removing errors" questions about functions, check def (not Def or define), the brackets and the colon on the header, the indented body, and that a call has brackets: Sum_Odd(), not Sum_Odd. A name like Sum-Odd is invalid.
FUNC.03 · Functions
Arguments and Parameters
12-CS
A parameter (formal parameter) is a name in the function's header. An argument (actual parameter) is the value passed in the call. When the function is called, each parameter is given the value of its argument. Python matches them in three ways.
Positional arguments fill parameters in order; keyword arguments name the parameter; a parameter with a default needs no argument at all.
With positional arguments the first argument goes to the first parameter, the second to the second, and so on. The number of arguments must match, and the order matters.
Python · order decides
def power(base, exp):
return base ** exp
print(power(2, 5)) # base = 2, exp = 5
print(power(5, 2)) # base = 5, exp = 2
A default parameter has a value in the header, r=8, used when the call gives no argument for it. Parameters with defaults must come after all parameters without defaults.
Python · defaults fill the gaps
def interest(p, r=8, t=1):
return p * r * t / 100
print(interest(5000))
print(interest(5000, 10))
print(interest(5000, 10, 3))
Output
400.0
500.0
1500.0
Python · a default before a non-default
def interest(p, r=8, t):
return p * r * t / 100
Output
File "main.py", line 1
def interest(p, r=8, t):
^
SyntaxError: parameter without a default follows parameter with a default
Named (keyword) arguments give the parameter's name in the call, t=2, so they can be in any order. Positional arguments may be mixed in, but must come first, and no parameter may get two values.
Python · by name
def interest(p, r=8, t=1):
return p * r * t / 100
print(interest(t=2, p=5000))
print(interest(5000, t=3))
Output
800.0
1200.0
Python shell · the rules
>>> def diff(a, b):
... return a - b
...
>>> diff(b=2, a=9)
7
>>> diff(9, b=2)
7
>>> diff(a=9, 2)
File "<stdin>", line 1
diff(a=9, 2)
^
SyntaxError: positional argument follows keyword argument
>>> diff(9, a=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: diff() got multiple values for argument 'a'
When a function is called, Python does not copy the argument. The parameter becomes a second name for the same object the caller passed. What happens next depends on two things: whether that object is mutable (list, dictionary) or immutable (int, float, str, tuple), and whether the function changes the object or gives the parameter a new value.
In every case the parameter starts as a second name for the caller's object (dotted arrow: "at the call"). Only changing a mutable object in place reaches back to the caller; giving the parameter a new value with = only moves the parameter.
Argument
Inside the function
Does the caller see it?
Immutable: int, float, str, tuple
Any change, e.g. x = x + 5, s += '!'
✗ No: a new object is made; only the parameter moves to it
Mutable: list, dictionary
Changed in place: L.append(4), L[0] = 9, L += [9], d[k] = v
✓ Yes: there is only one object
Mutable: list, dictionary
Given a new value: L = [0], L = L + [9]
✗ No: the parameter now names a new object
A copy of a list: f(m[:]), f(list(m))
Anything
✗ No: the function only ever had the copy
Immutable arguments
Python · an int: the caller keeps 10
def add_five(x):
x = x + 5 # x now names a new int
print('inside :', x)
n = 10
add_five(n)
print('outside:', n)
Output
inside : 15
outside: 10
Python · a string: s += makes a new string
def shout(s):
s += '!' # makes a new str
return s
word = 'hi'
print(shout(word), word)
Output
hi! hi
Mutable arguments
Python · changed in place: the caller sees it
def add4(L):
L.append(4) # changes the list itself
print('inside :', L)
m = [1, 2, 3]
add4(m)
print('outside:', m)
Output
inside : [1, 2, 3, 4]
outside: [1, 2, 3, 4]
Python · given a new list: the caller does not
def reset(L):
L = [0] # L now names a NEW list
print('inside :', L)
m = [1, 2, 3]
reset(m)
print('outside:', m)
Output
inside : [0]
outside: [1, 2, 3]
The two ways of adding to a list look alike but behave differently: L += [9] changes the list in place, while L = L + [9] builds a new list and moves L to it.
Python · += versus = … +
def grow(L):
L += [9] # in place: same list grows
def grow2(L):
L = L + [9] # builds a new list
a = [1]
b = [1]
grow(a)
grow2(b)
print(a, b)
To protect the caller's list, pass a copy: m[:] or list(m).
Python · a copy, then the list itself
def add4(L):
L.append(4)
m = [1, 2, 3]
add4(m[:]) # pass a copy
print(m)
add4(m) # pass the list itself
print(m)
Output
[1, 2, 3]
[1, 2, 3, 4]
Exam tip
"Which function header is correct?" Only one where every default comes after the non-defaults: def discount(rate, qty, dis=5) ✓; def discount(rate=7, qty, dis=5) ✗. In a call, keyword arguments after positional ones: f(5, b=2) ✓, f(a=5, 2) ✗.
FUNC.04 · Functions
Function Returning Values
12-CS
The return statement ends the function at once and sends a value back to the caller, where the call is replaced by that value. A function that returns a value can be used in expressions; a function that only prints shows something but gives back None.
Python · return versus print
def square(x):
return x * x
def show(x):
print(x * x)
a = square(4)
b = show(4)
print(a, b)
Output
16
16 None
No return, or a bare return: the function gives None.
Several values: return a, b packs them into a tuple, which the caller can unpack (TUP.01).
A function can have several return statements; the first one reached ends it, so code after it never runs.
def is_prime(n):
if n < 2:
return False
for d in range(2, n):
if n % d == 0:
return False # leaves at once
return True
print(is_prime(29), is_prime(91), is_prime(1))
Output
True False False
Exam tip
Assertion "a function can return multiple values"; Reason "they are returned as a tuple": both true, and R explains A. When a function both prints and is printed, as in print(show(4)), you get the function's own output first, then None.
FUNC.05 · Functions
Flow of Execution
12-CS
The flow of execution is the order in which statements actually run. Python starts at the first line of the program. A def is read and remembered, but its body is skipped. When a call is reached, control jumps into the function, runs its body, and on return (or at the end of the body) comes back to the line of the call, which then finishes.
Each call is a round trip: in through the header, through the body, and back to exactly where it was called from.
Python · numbered prints show the order
def area(l, b):
print('2. inside area')
return l * b
print('1. before the call')
x = area(4, 5)
print('3. back again, x =', x)
Output
1. before the call
2. inside area
3. back again, x = 20
Exam tip
"Write the flow of execution as line numbers": list the def header line first (it is read), skip its body, follow the main lines, and at each call write the body's lines, then the call line again. For the program above: 1 → 5 → 6 → 1 → 2 → 3 → 6 → 7.
FUNC.06 · Functions
Scope of a Variable
12-CS
The scope of a variable is the part of the program where its name can be used. A name made at the top level of the program is global; a name made inside a function (including its parameters) is local to that function and exists only while the function runs. When a name is used, Python looks for it in the order Local → Enclosing → Global → Built-in (the LEGB rule; "enclosing" means a function inside another function).
A function can see outwards (it can read globals) but the program cannot see in: count does not exist outside show().
A global variable is created outside every function. Any function can read it. To assign to it inside a function, declare it first with global name; otherwise the assignment creates a new local variable with the same name.
Python · reading a global
total = 100 # global variable
def show():
print('inside :', total) # read it
show()
print('outside:', total)
Output
inside : 100
outside: 100
Python · changing a global
x = 10
def change():
global x # use the global x
x = x * 2
change()
print(x)
A local variable is created inside a function. It is made fresh on each call and disappears when the function ends, so using it outside is a NameError. A local name can hide a global with the same name: inside the function the local one is used.
inside: 5
Traceback (most recent call last):
File "main.py", line 6, in <module>
print(count)
NameError: name 'count' is not defined
Python · a local hides the global
x = 10
def f():
x = 99 # a new, local x
print('local x =', x)
f()
print('global x =', x)
Output
local x = 99
global x = 10
Python · assigning without global
c = 10
def add():
c = c + 2
add()
Output
Traceback (most recent call last):
File "main.py", line 6, in <module>
add()
File "main.py", line 4, in add
c = c + 2
UnboundLocalError: cannot access local variable 'c' where it is not associated with a value
Because c is assigned inside add(), Python treats it as local in the whole function, so c + 2 reads a local that has no value yet.
Nested functions and the enclosing scope #nested-scope
A function can be defined inside another function. The outer function's local variables then form an extra scope for the inner one, called the enclosing scope: the E of LEGB. The inner function can read them, and it is itself local to the outer function, so it can only be called from there.
Python looks for a name from the inside out and uses the first scope that has it. A function can read every scope outside it, but nothing outside can see into a function.
Python · reading outward: L, E, G, B
x = 'global'
def outer():
y = 'enclosing'
def inner():
z = 'local'
print(z, y, x, len('abc')) # L E G B
inner()
outer()
Output
local enclosing global 3
When the same name exists at several levels, the innermost one hides the rest. Each function sees its own x.
Python · one name at three levels
x = 'global'
def outer():
x = 'enclosing'
def inner():
x = 'local'
print('inner sees:', x)
inner()
print('outer sees:', x)
outer()
print('main sees :', x)
Output
inner sees: local
outer sees: enclosing
main sees : global
global always jumps straight to the global scope, skipping the enclosing one. (Python also has nonlocal to change an enclosing variable, but it is not in the syllabus.)
Python · global skips the enclosing scope
count = 0
def outer():
count = 10
def inner():
global count # the GLOBAL count,
count += 1 # not outer's
inner()
print('outer count :', count)
outer()
print('global count:', count)
Output
outer count : 10
global count: 1
Python · an inner function is local to outer()
def outer():
def inner():
print('hello from inner')
inner()
outer()
inner()
Output
hello from inner
Traceback (most recent call last):
File "main.py", line 7, in <module>
inner()
NameError: name 'inner' is not defined
Exam tip
Output questions with global and end= are asked every year. Trace the global's value line by line, and remember that end='@@' keeps everything on one line: i = 5, print, add 7 inside, print, print again gives 5@@12##12.
Chapter practice · FUNC
Check your understanding
Predict the output
i = 5
print(i, end='@@')
def add():
global i
i = i + 7
print(i, end='##')
add()
print(i)
5@@12##12
5 is printed first; add() changes the global i to 12 and prints it; the last print shows the changed global.
def swap(A, B):
A, B = B, A
print(A, '#', B)
return A
C = 120
D = 240
C = swap(C, D)
print(C, '#', D)
240 # 120
240 # 240
Inside, A and B are swapped locals: 240 # 120. The function returns A (240) into C; D is untouched.
def f(a, b=2, c=3):
return a + b * c
print(f(1), f(1, c=1), f(c=2, a=3))
7 3 7
1 + 2 × 3 = 7; 1 + 2 × 1 = 3; with a = 3, c = 2 and the default b = 2: 3 + 2 × 2 = 7.
c = 10
def add():
global c
c = c + 2
print(c, end='#')
add()
c = 15
print(c, end='%')
10#15%
10 is printed before add() runs; add() makes c 12, but c = 15 replaces it before the second print.
def change(a, b):
a = a * 2
b[0] = b[0] * 2
x = 5
y = [5]
change(x, y)
print(x, y)
5 [10]
a = a * 2 only moves the parameter a to a new int, so x stays 5. b[0] = … changes the list itself, so y becomes [10].
a = 1
def f():
a = 2
def g():
print(a, end=' ')
g()
print(a, end=' ')
f()
print(a)
2 2 1
g() has no a of its own, so it reads the enclosing a of f(), 2. f() prints its own a, 2. The main program sees the global a, 1.
def update(nums, n):
for value in range(n):
if nums[value] % 3 == 0:
nums[value] %= 4
if nums[value] % 2 == 0:
nums[value] *= 2
lst = [81, 82, 18, 48, 99, 60, 25]
update(lst, 4)
for ele in lst:
print(ele, end='#')
1#164#4#0#99#60#25#
The function changes the caller's list in place (only the first 4 items): 81 → 1, 82 → 164, 18 → 2 → 4, 48 → 0.
Self-check quiz
Which function header is correct?
Parameters with defaults must come after all those without.
A function with no return statement returns:
Reaching the end of the body returns None.
return a, b sends back:
The comma packs the values into a tuple.
In def area(l, b): and the call area(4, 5), the values 4 and 5 are:
Values in the call are arguments; names in the header are parameters.
Which call is a SyntaxError for def f(a, b):?
A positional argument may not follow a keyword argument.
In def change(): n = 10; x = 5, n and x are:
Names assigned inside a function are local to it.
Which statement lets a function assign to a global variable x?
global x makes the assignment change the global name.
In the LEGB rule, which scope is searched first?
Local, then Enclosing, Global, Built-in.
A list passed to a function is changed inside it with L.append(9). After the call:
The function received a reference to the same list object.
Your score
– / 9
Answer every question to see your score.
One-page revision
3 typesbuilt-in · module · user-defined
def f(a, b):header: name, parameters, colon
Parameter · argumentname in the header · value in the call
Positionalmatched by order
Defaultb=2 in the header; after non-defaults
Namedf(b=2, a=1); after positional ones
returnends the function, sends a value
No returngives None
return a, ba tuple
Mutable argumentchanged in place: the caller sees it
Immutable argumentthe caller never sees a change
Localmade inside; gone after the call
global xassign to the global inside a function
LEGBlocal → enclosing → global → built-in
Enclosinglocals of the outer function, seen by an inner one
Chapter 14 of 19 · EXC
Exception Handling
A runtime error normally stops a program with a traceback. Exception handling lets the program catch the error, deal with it (tell the user, use a default, tidy up) and carry on. It matters most for input and files, where things go wrong that the programmer can't prevent.
EXC.01 · Exception Handling
Introduction to Exception Handling
12-CS
An exception is an error that happens while the program is running: a runtime error (ERR.01), such as dividing by zero or converting 'ninety' to an int. Python raises an exception object of a particular type (ZeroDivisionError, ValueError …). If nothing handles it, the program stops at that line and prints a traceback. Exception handling is writing code that catches the exception and responds, so the program does not crash.
Python · not handled: the program stops
print('Start')
marks = int('ninety')
print('End')
Output · 'End' is never printed
Start
Traceback (most recent call last):
File "main.py", line 2, in <module>
marks = int('ninety')
ValueError: invalid literal for int() with base 10: 'ninety'
Python · handled: the program carries on
print('Start')
try:
marks = int('ninety')
except ValueError:
print('Marks must be a number')
print('End')
Output
Start
Marks must be a number
End
Built-in exception
Raised when
ZeroDivisionError
Dividing by zero
ValueError
The value is wrong for the operation: int('abc')
TypeError
The type is wrong: '5' + 5
NameError
A name that is not defined
IndexError · KeyError
A list index out of range · a missing dictionary key
FileNotFoundError
Opening a missing file for reading
EOFError
Reading past the end of a file, e.g. pickle.load() (BIN.02)
ImportError
An import fails (ModuleNotFoundError is one kind)
Exam tip
A syntax error can't be handled: the program never starts. Exception handling is only for errors that happen while it runs. "Which exception is raised when an operator gets a value of the wrong type?" TypeError; a right type but unsuitable value is ValueError.
EXC.02 · Exception Handling
try-except-finally Blocks
12-CS
Exceptions are handled with up to four blocks. try holds the risky code; one or more except blocks say what to do for each kind of error; an optional else runs only if no error happened; an optional finally runs always, error or not.
Every path ends at finally, which is why it is used for clean-up work such as closing a file. Of else and except, at most one runs.
The try block holds the statements that might raise an exception. If one of them does, the rest of the try block is skipped and Python jumps to the matching except. A try must be followed by at least one except or a finally.
An except ErrorName: block runs when the try raises that kind of exception. There can be several; Python checks them from the top and runs only the first one that matches. except Exception: (or a bare except:) matches almost any error, so it belongs last. except ValueError as e: also gives the error's message in e.
Python · one except per error
try:
n = int(input('Enter a number: '))
print('100 /', n, '=', 100 / n)
except ValueError:
print('That was not a whole number.')
except ZeroDivisionError:
print('Cannot divide by zero.')
print('The program goes on.')
Output · three runs: 8, ten, 0
Enter a number: 8
100 / 8 = 12.5
The program goes on.
Enter a number: ten
That was not a whole number.
The program goes on.
Enter a number: 0
Cannot divide by zero.
The program goes on.
Python · the error's message
L = [10, 20]
try:
print(L[5])
except Exception as e:
print('Something went wrong:', e)
Output
Something went wrong: list index out of range
Python · a bare except catches everything
try:
print(undefined_name)
except:
print('some error was caught')
Output
some error was caught
Python · a board question: the order of excepts
try:
x = 18 // 0
except Exception:
print('Exception occurred!')
except ZeroDivisionError:
print('Division by zero error!')
Output
Exception occurred!
ZeroDivisionError is a kind of Exception, so the first except already matches, and the second is never reached.
else
An optional else: after the excepts runs only when the try finished without an exception: a good place for code that should run only on success.
The finally: block runs every time: after the try succeeds, after an except handles an error, and even when an error is not handled at all (it runs first, then the error stops the program). It is used to release resources, such as closing a file.
Python · all four blocks
def divide(a, b):
try:
print('result:', a / b)
except ZeroDivisionError:
print('error: cannot divide by 0')
else:
print('else: no error happened')
finally:
print('finally: always runs')
divide(10, 4)
print('---')
divide(10, 0)
Output
result: 2.5
else: no error happened
finally: always runs
---
error: cannot divide by 0
finally: always runs
finally runs first
Traceback (most recent call last):
File "main.py", line 2, in <module>
total = 'Total: ' + 50
TypeError: can only concatenate str (not "int") to str
Exam tip
True or False: "a try block can exist without an except block as long as a finally block is present": True. "When does else run?" When no exception occurs. "Is finally always executed?" Yes. In output questions, once an error happens in try, skip the rest of the try block.
5 / 0 fails, so B is skipped; except prints C; else is skipped; finally prints E.
try:
value = input('Enter a number: ') + 100
except ValueError:
print('Value Error occurred!')
except ZeroDivisionError:
print('Division by zero error!')
except Exception:
print('Some other error!')
Enter a number: 5
Some other error!
input() gives the string '5'; '5' + 100 is a TypeError, which only the last except (Exception) matches.
int('abc') raises ValueError; the first matching except runs and the rest are skipped.
Self-check quiz
When is the else part of try-except-else executed?
else runs only if the try block raised nothing.
Which is true about try-except-finally?
finally runs whether or not an exception occurred.
Which error can NOT be handled with try-except?
A syntax error stops the program before it runs.
Where should except Exception: go among several except blocks?
It matches almost everything, so any except after it would never run.
If an error in try is not matched by any except:
finally still runs; the unhandled error then gives a traceback.
Your score
– / 5
Answer every question to see your score.
One-page revision
Exceptionan error while the program runs
try:risky code; stops at the first error
except E:runs for error type E; first match only
except Exceptioncatches almost all; put it last
as ethe error's message
else:runs only when there was no error
finally:runs always; for clean-up
try + finallyallowed without except
Syntax errorscan't be caught
TypeError · ValueErrorwrong type · wrong value
Chapter 15 of 19 · FILE
Introduction to Files
Variables live in memory and vanish when a program ends. To keep data (marks, records, logs) for next time, a program writes it to a file on the disk. This short chapter sets up the next three: the three kinds of file Python works with, and how to name where a file is.
FILE.01 · Introduction to Files
Types of Files
12-CS
A file is a named collection of data stored on secondary storage (a disk or pen drive), so it lasts after the program ends. Data file handling means opening a file, reading or writing it, and closing it. Python handles three kinds of data file.
CSV is a kind of text file with a fixed layout. A binary file is the odd one out: its bytes only make sense to the program that wrote them.
A text file stores data as human-readable characters (ASCII or Unicode), arranged in lines. Each line ends with an EOL (end of line) character, '\n' in Python. Any editor such as Notepad can open it. Extension: .txt (also .py, .html). Chapter TXT.
A binary file stores data as bytes, in the same form as it is held in memory, with no lines and no EOL. It is compact and fast to read back, but opening it in Notepad shows nonsense. Python writes whole objects (lists, dictionaries) into it with the pickle module. Extension: often .dat. Chapter BIN.
A CSV (comma-separated values) file is a text file that stores a table: one row per line, values separated by commas, often with a header row first. Spreadsheets such as Excel open and save it. Extension: .csv. Chapter CSV.
Python · the same record, three ways
import pickle, csv
with open('marks.txt', 'w') as f: # text
f.write('Asha 91\n')
with open('marks.dat', 'wb') as f: # binary
pickle.dump(['Asha', 91], f)
with open('marks.csv', 'w', newline='') as f:
csv.writer(f).writerow(['Asha', 91]) # CSV
print(open('marks.txt').read(), end='')
print(open('marks.csv').read(), end='')
print(open('marks.dat', 'rb').read())
Assertion "binary files store data as it is stored in memory": true. Reason "binary files can be edited in Notepad": false. "Differentiate text and binary files" needs readability, EOL and how each is read.
FILE.02 · Introduction to Files
Relative and Absolute Paths
12-CS
A path tells Python where a file is in the tree of folders (directories). An absolute path starts from the root of the drive and gives every folder on the way, so it works from anywhere. A relative path starts from the current working directory (normally the folder of the running program), so it is shorter and still works if the whole project is moved. .. means "the parent folder".
Windows separates folders with \; Linux and macOS use /. Python accepts / on every system.
Python · a relative path, and a wrong one
f = open('school/data/marks.txt') # relative
print(f.read(), end='')
f.close()
f = open('data/marks.txt') # wrong folder
Output
Asha 91
Traceback (most recent call last):
File "main.py", line 4, in <module>
f = open('data/marks.txt') # wrong folder
FileNotFoundError: [Errno 2] No such file or directory: 'data/marks.txt'
Writing a Windows path in Python
Inside a string, a backslash starts an escape: \n is a newline and \t a tab. So 'C:\new\data.txt' is broken. Double every backslash, put r before the string (a raw string, where backslashes are ordinary), or use forward slashes.
Define both with an example: absolute C:\School\Data\marks.txt (from the root), relative Data\marks.txt (from the current folder). A file name alone, open('marks.txt'), is a relative path: the file must be in the current folder.
Chapter practice · FILE
Check your understanding
Self-check quiz
Which file stores data in the same format as in memory?
A binary file holds raw bytes; text and CSV files hold characters.
The EOL character in Python is:
Each line of a text file ends with '\n'.
A CSV file is:
CSV is plain text with a table layout.
Which is an absolute path?
It starts from the root of the drive.
In a path, .. means:
A single dot is the current folder; two dots go one level up.
Your score
– / 5
Answer every question to see your score.
One-page revision
Filenamed data on disk; lasts after the program
Text filecharacters in lines; '\n' ends each line
Binary filebytes as in memory; pickle; not readable
CSV filetext rows, comma-separated values
Absolute pathfrom the root: C:\School\a.txt
Relative pathfrom the current folder: Data\a.txt
..the parent folder
r'C:\new'raw string: \ is not an escape
Chapter 16 of 19 · TXT
Text File
Opening, writing, reading and moving around in a text file. Board papers carry a 3-mark program on text files every year ("count the words …", "display the lines that start with …"), so the last topic is all such programs, run on one sample file.
Note
Every reading example in this chapter uses this sample file, story.txt. Its first two lines are from a board question.
story.txt
My first book was Me and My Family.
It gave me a chance to be known to the world.
The world has 195 countries.
A book a day keeps boredom away.
The program map
Every text-file question (write lines, count words, show certain lines) asks for a function with the same few parts. Learn this shape first; the topics below fill in each step.
The filled step is the one that changes from question to question: which read method to use, or what to write. Everything else is the same every time.
TXT.01 · Text File
Opening and Closing a Text File
12-CS
open(filename, mode) opens a file and returns a file object (also called a file handle), through which the program reads and writes. The mode says what you mean to do (TXT.02); if it is left out, it is 'r', read. When the work is done, f.close() closes the file: it saves any data still waiting in memory (the buffer) to the disk and frees the file for other programs.
Python · open, use, close
f = open('story.txt', 'r')
print(type(f))
print(f.name, f.mode, f.closed)
data = f.read()
f.close()
print(f.closed)
Output
<class '_io.TextIOWrapper'>
story.txt r False
True
with open(…) as f: opens the file and closes it automatically when the indented block ends, even if an error happens inside it. No close() is needed, and none can be forgotten.
Python · with closes the file
with open('story.txt') as f:
first = f.readline()
print('inside :', f.closed)
print('outside:', f.closed)
print(first, end='')
Output
inside : False
outside: True
My first book was Me and My Family.
Exam tip
Syntax to learn: f = open('story.txt', 'r') … f.close(), or with open('story.txt') as f:. The advantage of with: the file is closed automatically. Forgetting close() after writing can leave the data unsaved.
TXT.02 · Text File
Text File Open Modes
12-CS
The mode decides three things: whether the file must already exist, whether its old contents are kept, and where the file pointer (the position of the next read or write) starts. A + adds the missing ability: reading to a write mode, or writing to the read mode.
The blue lines mark where the pointer is just after opening. Each read or write then moves it on by the number of characters used.
'r' opens an existing file for reading only. A missing file is an error.
Python · r on a missing file
f = open('nofile.txt', 'r')
Output
Traceback (most recent call last):
File "main.py", line 1, in <module>
f = open('nofile.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'nofile.txt'
'r+' reads and writes an existing file. Nothing is erased; a write overwrites characters at the pointer.
Python · r+ overwrites in place
with open('code.txt', 'w') as f:
f.write('ABCDEFGH')
with open('code.txt', 'r+') as f:
print(f.read(3)) # reads ABC
f.seek(0)
f.write('xy') # overwrites A and B
print(open('code.txt').read())
'w' creates the file, or empties it if it exists, and writes from the start.
Python · w replaces the old contents
with open('notes.txt', 'w') as f:
f.write('first version\n')
with open('notes.txt', 'w') as f: # empties it
f.write('second version\n')
print(open('notes.txt').read(), end='')
'a' (append) keeps the old data and adds new writes at the end; it creates the file if needed.
Python · a adds to the end
with open('log.txt', 'w') as f:
f.write('line 1\n')
with open('log.txt', 'a') as f: # add at the end
f.write('line 2\n')
print(open('log.txt').read(), end='')
'a+' appends and can also read; seek(0) to read from the start. Writes still go to the end.
Python · append, then read it all
with open('log.txt', 'w') as f:
f.write('line 1\n')
with open('log.txt', 'a+') as f:
f.write('line 2\n')
f.seek(0) # back to read
print(f.read(), end='')
Output
line 1
line 2
Exam tip
"Which mode keeps the old data and adds new data?" 'a'. "Which mode gives FileNotFoundError for a missing file?" 'r' and 'r+'. "Difference between w and a?" w erases, a keeps and adds at the end.
TXT.03 · Text File
Writing to a Text File
12-CS
Open the file in 'w' or 'a' mode, then write strings to it. Python writes exactly what you give it: it adds no spaces and no newlines of its own, so put '\n' at the end of each line yourself.
f.write(s) writes the string s and returns the number of characters written. Its argument must be a string: convert numbers with str().
Python · write() and newlines
f = open('class.txt', 'w')
n = f.write('Asha\n')
print('characters written:', n)
f.write('Ravi') # no newline is added
f.write(str(17) + '\n') # numbers need str()
f.close()
print(open('class.txt').read(), end='')
Output
characters written: 5
Asha
Ravi17
Python · writing a number
f = open('class.txt', 'w')
f.write(17)
Output
Traceback (most recent call last):
File "main.py", line 2, in <module>
f.write(17)
TypeError: write() argument must be str, not int
Python · lines typed by the user
with open('diary.txt', 'w') as f:
n = int(input('How many lines? '))
for i in range(n):
f.write(input('Line: ') + '\n')
print(open('diary.txt').read(), end='')
Output · the user types 2 lines
How many lines? 2
Line: Exams start on Monday
Line: Revise files first
Exams start on Monday
Revise files first
f.writelines(L) writes every string in a list (or tuple) one after another. Despite its name it adds no newlines: the strings must already end with '\n' if you want separate lines. It returns None.
Python · writelines()
names = ['Asha\n', 'Ravi\n', 'Meena\n']
with open('names.txt', 'w') as f:
f.writelines(names)
f.writelines(['no', 'newline'])
print(open('names.txt').read())
Output
Asha
Ravi
Meena
nonewline
Exam tip
"Differentiate write() and writelines()": write takes one string and returns the count of characters; writelines takes a list of strings and returns None. Neither adds '\n'.
TXT.04 · Text File
Reading from a Text File
12-CS
Open the file in 'r' mode (or any mode with +). Three methods read from the pointer onwards, and each moves the pointer past what it read. They differ in how much they read and what type they return.
read() and readline() give a string; readlines() gives a list of strings. All of them keep the '\n' at the end of each line.
f.read() reads everything from the pointer to the end, as one string. f.read(n) reads at most n characters.
Python · read(n), then the rest
f = open('story.txt')
print(f.read(9)) # 9 characters
print(f.read(9)) # the next 9
rest = f.read() # everything left
f.close()
print(len(rest), 'characters were left')
f.readlines() reads all the remaining lines into a list, one string per line. len() of it is the number of lines. Printing a line prints its '\n' too, so use end='' or strip().
Python · a list of lines
with open('story.txt') as f:
lines = f.readlines()
print(type(lines), len(lines))
print(lines[2])
print(lines[-1].strip())
Output · note the blank line from '\n'
<class 'list'> 4
The world has 195 countries.
A book a day keeps boredom away.
The simplest way to go through a file is a for loop over the file object itself: it gives one line per iteration.
Python · loop over the lines
with open('story.txt') as f:
for line in f: # one line at a time
print('>', line.strip())
Output
> My first book was Me and My Family.
> It gave me a chance to be known to the world.
> The world has 195 countries.
> A book a day keeps boredom away.
Python · reading at the end
f = open('story.txt')
f.read()
print(repr(f.read()), repr(f.readline()))
f.close()
Output
'' ''
Exam tip
Choose by the task: counting characters or words → read() (then split() for words); working on lines → a for loop or readlines(). "Return type of readlines()?" list.
TXT.05 · Text File
seek and tell Methods
12-CS
The file pointer is a position counted in bytes from the start of the file, beginning at 0. tell() reports where it is; seek() moves it, so the next read or write happens there.
The pointer always sits between characters. Position 10 means 10 characters are behind it, and the next read starts with the character numbered 10.
f.seek(offset, whence) moves the pointer by offset bytes from a reference point, whence: 0 the start (the default), 1 the current position, 2 the end. In a text file only seeks from the start are reliable (seek(n), plus seek(0, 2) to jump to the end); for other moves open the file in binary mode.
Python · tell and seek
f = open('story.txt', 'r')
d = f.read(10)
print(f.tell()) # where the pointer is
f.seek(0) # back to the start
print(f.read(2), f.tell())
f.seek(3)
print(f.read(10))
f.close()
Output
10
My 2
first book
Python · from the end, in binary mode
f = open('story.txt', 'rb')
f.seek(-6, 2) # 6 bytes before the end
print(f.read())
f.seek(0, 2)
print(f.tell()) # the file's size in bytes
f.close()
Output · 144 bytes in all
b'away.\n'
144
Exam tip
Fill in the blank after d = f.read(50) to print the pointer's position: print(f.tell()), and the answer is 50 (for a file of plain English text). "Difference between seek() and tell()": tell reports the position; seek moves it.
TXT.06 · Text File
Manipulation of Data in a Text File
12-CS
Board questions ask for a function that opens a text file and counts, shows or changes part of it. Nearly all follow one of four patterns. Each program below runs on story.txt from the top of the chapter.
Task
Pattern
Count characters (vowels, digits, capitals)
text = f.read(), then for ch in text:
Count words, or a particular word
words = f.read().split(), then for w in words:
Show or count certain lines
for line in f:, test line[0], line.startswith() or in line
Change the file
Read it all, change the string, open again in 'w' and write it back; or copy wanted lines to a new file
Counting words
Python · a board question: count Me or My
def count_me_my():
c = 0
with open('story.txt') as f:
for word in f.read().split():
if word.lower() in ('me', 'my'):
c += 1
print('Count of Me/My in file:', c)
count_me_my()
Output
Count of Me/My in file: 4
Python · all words, and "the"
def count_the():
with open('story.txt') as f:
words = f.read().split()
c = 0
for w in words:
if w.lower() == 'the':
c += 1
print('Words:', len(words), ' the:', c)
count_the()
Output
Words: 31 the: 2
Lines that start with a letter
Python · show and count lines
def show_TA():
count = 0
with open('story.txt') as f:
for line in f:
if line[0] in 'TA':
print(line, end='')
count += 1
print('Lines starting with T or A:', count)
show_TA()
Output
The world has 195 countries.
A book a day keeps boredom away.
Lines starting with T or A: 2
Counting characters
Python · vowels, digits, capitals
def count_chars():
with open('story.txt') as f:
text = f.read()
v = d = u = 0
for ch in text:
if ch.isdigit():
d += 1
if ch.isupper():
u += 1
if ch in 'aeiouAEIOU':
v += 1
print('vowels', v, 'digits', d, 'upper', u)
count_chars()
Output
vowels 40 digits 3 upper 7
Copying some lines to another file
Python · lines with "world" into world.txt
def copy_world():
with open('story.txt') as src, \
open('world.txt', 'w') as dst:
for line in src:
if 'world' in line:
dst.write(line)
copy_world()
print(open('world.txt').read(), end='')
Output · world.txt
It gave me a chance to be known to the world.
The world has 195 countries.
Changing the file
A text file can't be edited in the middle like a list. Read the whole text, change the string, and write it all back with 'w'.
Python · replace a word everywhere
def replace_word(old, new):
with open('story.txt') as f:
text = f.read()
with open('story.txt', 'w') as f:
f.write(text.replace(old, new))
replace_word('book', 'novel')
print(open('story.txt').read(), end='')
Output · story.txt afterwards
My first novel was Me and My Family.
It gave me a chance to be known to the world.
The world has 195 countries.
A novel a day keeps boredom away.
Exam tip
Follow the program map: def, open with the right file name and mode, the loop, the condition, the count and the print. Mind case: "the" vs "The" (use lower() if the question says "irrespective of case"), and punctuation stuck to words ("world." is not "world" unless you strip('.')).
Chapter practice · TXT
Check your understanding
Predict the output
f = open('story.txt')
print(f.read(5))
print(f.tell())
f.seek(12)
print(f.readline(), end='')
f.close()
My fi
5
k was Me and My Family.
read(5) takes "My fi" and leaves the pointer at 5. seek(12) jumps to the 'k' of "book"; readline() reads from there to the end of that line.
with open('a.txt', 'w') as f:
f.write('One')
with open('a.txt', 'a') as f:
f.write('Two')
with open('a.txt', 'w') as f:
f.write('Three')
print(open('a.txt').read())
Three
'a' added Two after One, but the last 'w' erased everything before writing Three.
with open('story.txt') as f:
L = f.readlines()
print(len(L), L[1].split()[1])
4 gave
story.txt has 4 lines. L[1] is "It gave me …"; its second word is "gave".
Self-check quiz
Which mode opens a text file to add data at the end, keeping what is there?
Append mode writes after the existing data.
f.readlines() returns:
Each line becomes one string in the list.
What does f.read(5) return?
read(n) reads n characters from the pointer.
Opening a file that does not exist in 'w' mode:
w (and a) create the file if needed; r and r+ do not.
Which statement gives the file pointer's current position?
tell() reports, seek() moves.
f.writelines(['a', 'b']) writes:
writelines adds no newlines.
The main advantage of with open(…) as f: is:
The file closes when the block ends, even after an error.
Your score
– / 7
Answer every question to see your score.
One-page revision
open(name, mode)returns a file object; default 'r'
close() · withsave and release · closes automatically
r · r+file must exist; pointer at start
w · w+creates or erases; pointer at start
a · a+creates or keeps; writes at the end
write(s)one string; returns its length
writelines(L)list of strings; no '\n' added
read() · read(n)all · n characters; a string
readline()one line with its '\n'; '' at the end
readlines()a list of all the lines
tell() · seek(n)where the pointer is · move it to n
Count wordsf.read().split()
Chapter 17 of 19 · BIN
Binary File
A binary file keeps Python objects (whole lists and dictionaries) exactly as they are, using the pickle module. Board papers give a record layout such as [roll, name, marks] and ask for functions to add, show, search and update records; every one of those patterns is here.
Note
Most examples use stu.dat, a binary file of four records [roll, name, marks]: [1, 'Asha', 91.0], [2, 'Ravi', 72.0], [3, 'Meena', 85.0] and [4, 'Kabir', 64.0]. The examples that change the file then call show_all(), the read function from BIN.03, to show the result.
The program map
A binary-file question usually has two or three parts: add records, show or search them, and sometimes update or delete. Each part is one function, and each has this shape.
Reading is always the same loop: load inside while True, inside try, ending at EOFError. Only the test in step 4 changes. Updating is reading and writing joined together.
BIN.01 · Binary File
Binary File Open Modes
12-CS
Binary modes are the text modes with a b added. They behave the same way (TXT.02) as to whether the file must exist, whether old data is kept and where the pointer starts, but they read and write bytes instead of characters. pickle needs a binary mode.
'rb' reads an existing binary file; the pointer starts at the beginning. It never creates a file.
Python · rb on a missing file
f = open('none.dat', 'rb')
Output
Traceback (most recent call last):
File "main.py", line 1, in <module>
f = open('none.dat', 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'none.dat'
'wb' creates the file, or erases an existing one, then writes from the start. Use it to create a fresh file, or to write back all records after changing them.
'ab' keeps the old records and adds new ones at the end; it creates the file if it does not exist. "Input data and append it to the file" questions use it.
'ab+' appends and can also read: seek(0) to read from the start; writes still go to the end.
Exam tip
"Which mode opens a binary file for reading and writing?" rb+. Assertion: "rb opens a file to read it without changing it": true. Reason: "in rb mode a missing file is created": false, it raises FileNotFoundError.
BIN.02 · Binary File
pickle Module
12-CS
import pickle gives two functions. Pickling (serialisation) turns a Python object, such as a list, tuple or dictionary, into a stream of bytes and writes it to a binary file. Unpickling reads the bytes back and rebuilds the same object, with its type intact.
dump writes one object each time it is called; load reads one object each time, in the same order.
pickle.load(fileobject) reads the next object from a file opened with 'rb' and returns it. When no objects are left it raises EOFError, which is how a program knows it has reached the end.
Python · dump a dictionary, load it back
import pickle
rec = {'roll': 1, 'name': 'Asha', 'marks': 91}
with open('stu.dat', 'wb') as f:
pickle.dump(rec, f) # object -> bytes
with open('stu.dat', 'rb') as f:
back = pickle.load(f) # bytes -> object
print(back)
print(back == rec, type(back))
import pickle
with open('stu.dat', 'wb') as f:
pickle.dump([1, 'Asha', 91], f)
pickle.dump([2, 'Ravi', 78], f)
f = open('stu.dat', 'rb')
print(pickle.load(f))
print(pickle.load(f))
print(pickle.load(f)) # nothing is left
Output
[1, 'Asha', 91]
[2, 'Ravi', 78]
Traceback (most recent call last):
File "main.py", line 8, in <module>
print(pickle.load(f)) # nothing is left
EOFError: Ran out of input
Exam tip
Learn the argument order: pickle.dump(rec, f), object first, file second; rec = pickle.load(f). "Correct way to load an object from a binary file?" pickle.load(file). Opening in text mode instead of binary gives a TypeError.
BIN.03 · Binary File
Operations on a Binary File
12-CS
Every operation is a function built from the same few lines: open in the right mode, then dump records, or load them in a while True loop that ends at EOFError. Changing records always means reading them all, changing them, and writing them all back.
Load records one by one until EOFError. Put the loop in try and catch EOFError to stop cleanly. This show_all() is used by the later examples.
Python · show every record
import pickle
def show_all():
with open('stu.dat', 'rb') as f:
try:
while True:
rec = pickle.load(f)
print(rec)
except EOFError: # end of file
pass
show_all()
Open with 'wb' (a new file) and dump one record per item entered.
Python · input records into a new file
import pickle
def create():
with open('stu.dat', 'wb') as f:
n = int(input('How many students? '))
for i in range(n):
roll = int(input('Roll: '))
name = input('Name: ')
marks = float(input('Marks: '))
pickle.dump([roll, name, marks], f)
create()
print(open('stu.dat', 'rb').read()[:24], '...')
Output · the user types 2 students; then the raw bytes
How many students? 2
Roll: 1
Name: Asha
Marks: 91
Roll: 2
Name: Ravi
Marks: 72
b'\x80\x04\x95\x17\x00\x00\x00\x00\x00\x00\x00]\x94(K\x01\x8c\x04Asha\x94G' ...
Load each record and test a field; keep a flag so you can say "not found" after the whole file has been read. Counting is the same pattern with a counter.
Python · search by roll number
import pickle
def search(roll):
found = False
with open('stu.dat', 'rb') as f:
try:
while True:
rec = pickle.load(f)
if rec[0] == roll:
print('Found:', rec)
found = True
except EOFError:
pass
if not found:
print('Roll', roll, 'not found')
search(3)
search(9)
Output
Found: [3, 'Meena', 85.0]
Roll 9 not found
Python · show and count, return the count
import pickle
def count_above(m):
c = 0
with open('stu.dat', 'rb') as f:
try:
while True:
rec = pickle.load(f)
if rec[2] > m:
print(rec[1], rec[2])
c += 1
except EOFError:
pass
return c
print('Above 80:', count_above(80))
The safe way: 1 read every record into a list, 2 change the ones that match, 3 open with 'wb' and dump them all back. Deleting records is the same, except that you keep only the records you want.
Python · change one field
import pickle
def update_marks(roll, new):
records = []
with open('stu.dat', 'rb') as f: # 1. read
try:
while True:
records.append(pickle.load(f))
except EOFError:
pass
for rec in records: # 2. change
if rec[0] == roll:
rec[2] = new
with open('stu.dat', 'wb') as f: # 3. write
for rec in records:
pickle.dump(rec, f)
update_marks(2, 95.0)
show_all()
import pickle
def delete_below(m):
keep = []
with open('stu.dat', 'rb') as f:
try:
while True:
rec = pickle.load(f)
if rec[2] >= m: # keep it
keep.append(rec)
except EOFError:
pass
with open('stu.dat', 'wb') as f:
for rec in keep:
pickle.dump(rec, f)
delete_below(70)
show_all()
Many marking schemes also accept an in-place update with 'rb+': remember the record's start with tell(), load it, seek() back and dump the changed record over it. This is safe only when the new record takes exactly as many bytes as the old one (here, one float replaced by another).
Python · update in place with tell and seek
import pickle
def update_inplace(roll, new):
with open('stu.dat', 'rb+') as f:
try:
while True:
pos = f.tell() # its start
rec = pickle.load(f)
if rec[0] == roll:
rec[2] = new
f.seek(pos) # go back
pickle.dump(rec, f)
break
except EOFError:
pass
update_inplace(4, 70.0)
show_all()
Each function in a binary-file answer follows the program map: import pickle, open with the right mode ('ab' to add, 'rb' to read, 'wb' to rewrite), the load loop with try … except EOFError, and the field test using the given structure (rec[2] for marks in [roll, name, marks], or rec['price'] for a dictionary).
Chapter practice · BIN
Check your understanding
Predict the output
import pickle
with open('t.dat', 'wb') as f:
pickle.dump((1, 2), f)
pickle.dump('end', f)
with open('t.dat', 'rb') as f:
a = pickle.load(f)
b = pickle.load(f)
print(a[1] * 2, b * 2, type(a))
4 endend <class 'tuple'>
Objects come back in the order they were dumped, with their types: a is the tuple (1, 2), b the string 'end'.
A program opens stu.dat with 'wb' to add one new record. What happens to the four records already there?
They are lost.wb erases the file first; to add records use 'ab'.
Self-check quiz
Which mode opens a binary file for reading and writing without erasing it?
rb+ keeps the data; wb+ would erase it; a+ is a text mode.
Which is the correct way to load an object from a binary file?
load reads one object; dump writes one.
Opening a missing file in 'rb' mode:
Only w and a modes create files.
pickle.load() raises which exception at the end of the file?
EOFError: Ran out of input.
The order of arguments in pickle.dump() is:
dump(object, fileobject).
To add a new record to an existing binary file, open it with:
ab keeps the old records and writes at the end.
Your score
– / 6
Answer every question to see your score.
One-page revision
rb · rb+read · read and write; file must exist
wb · wb+create or erase, then write
ab · ab+keep, add at the end
import pickleneeded for dump and load
dump(obj, f)write one object (pickling)
obj = load(f)read the next object (unpickling)
EOFErrorno more objects: stop reading
Read allwhile True: load … except EOFError
Searchload, test a field, flag for "not found"
Update · deleteread all → change → 'wb' write all
Chapter 18 of 19 · CSV
CSV File
A CSV file is a table saved as text: one row per line, values separated by commas. Python's csv module turns lists into such lines and back again, taking care of commas that appear inside the data.
The program map
CSV questions come in pairs, an add() or write function and a read function that counts or searches, and both have this shape.
Two lines are special to CSV: newline='' when opening, and converting a value with int() or float() before comparing it, because the reader gives strings.
CSV.01 · CSV File
csv Module
12-CS
The csv module (import csv) gives a writer object that turns a list into one CSV line, and a reader object that turns each line back into a list. A CSV file is a text file, so it is opened with the text modes 'r', 'w' and 'a'.
The filled box is the trap: the reader cannot know that 91 was a number, because the file holds only characters.
Open it like a text file, but pass newline='': the csv module writes its own line endings, and without this Windows gets an extra blank line after every row. Close it with close(), or use with.
To
Write
Create or overwrite
f = open('marks.csv', 'w', newline='')
Add rows at the end
f = open('marks.csv', 'a', newline='')
Read
f = open('marks.csv', 'r', newline='')
Close
f.close(), or open it with with … as f:
Exam tip
Assertion: "csv.reader returns each row as a list of strings": true. Reason: "the csv module converts numbers to integers": false. Remember import csv and newline='' in every CSV answer.
CSV.02 · CSV File
Writing to a CSV File
12-CS
Writing takes three steps: open the file ('w' to create, 'a' to add), make a writer, and give it rows. A row is a list or tuple; numbers are fine, the writer converts them to text.
w = csv.writer(f) makes a writer object for the open file f. An optional delimiter=';' uses another separator. If a value itself contains the delimiter, the writer puts quotes around it so that it stays one value.
Python · another delimiter, and quoting
import csv
with open('city.csv', 'w', newline='') as f:
w = csv.writer(f, delimiter=';')
w.writerow(['Kochi', 'Kerala'])
w.writerow(['New Delhi, India', 'Delhi'])
print(open('city.csv').read(), end='')
w.writerows(rows) writes many rows at once from a list of lists (a nested list).
Python · a heading, one row, then two more
import csv
with open('marks.csv', 'w', newline='') as f:
w = csv.writer(f)
w.writerow(['Roll', 'Name', 'Marks'])
w.writerow([1, 'Asha', 91])
w.writerows([[2, 'Ravi', 72],
[3, 'Meena', 85]])
print(open('marks.csv').read(), end='')
Output · marks.csv
Roll,Name,Marks
1,Asha,91
2,Ravi,72
3,Meena,85
Exam tip
"writerow() vs writerows()": writerow takes one list and writes one line; writerows takes a list of lists and writes a line for each. The board's ADD() functions open in 'a', input the fields, and call writerow([…]).
CSV.03 · CSV File
Reading from a CSV File
12-CS
Open the file with 'r', make a reader, and loop over it: each iteration gives one row as a list of strings.
r = csv.reader(f) makes a reader object. It is read once, from the top: for row in r: goes through every row, next(r) takes just the next one (useful to skip the heading), and list(r) gives all the rows as a nested list.
Python · every row
import csv
with open('marks.csv', newline='') as f:
r = csv.reader(f)
for row in r:
print(row)
import csv
with open('marks.csv', newline='') as f:
r = csv.reader(f)
next(r) # skip the heading
for row in r:
if int(row[2]) > 80: # values are str
print(row[1], row[2])
Output
Asha 91
Meena 85
Board questions: add, count, search
Python · add a record, count the records
import csv
def add():
with open('marks.csv', 'a', newline='') as f:
w = csv.writer(f)
roll = int(input('Roll: '))
name = input('Name: ')
marks = int(input('Marks: '))
w.writerow([roll, name, marks])
def count_rec():
with open('marks.csv', newline='') as f:
rows = list(csv.reader(f))
print('Records:', len(rows) - 1) # no heading
add()
count_rec()
Output · the user types 4, Kabir, 64
Roll: 4
Name: Kabir
Marks: 64
Records: 4
"Display the products whose price is more than 20000 and whose name starts with a vowel", from this Product.csv:
import csv
def search():
with open('Product.csv', newline='') as f:
for pid, pname, price in csv.reader(f):
if not price.isdigit(): # the heading
continue
if int(price) > 20000 and \
pname[0] in 'AEIOU':
print(pid, pname, price)
search()
Common mistake
Comparing row[2] > 80 compares a string with a number: TypeError. Convert first, int(row[2]) > 80, and skip the heading row, or int('Marks') fails with ValueError.
Chapter practice · CSV
Check your understanding
Predict the output
import csv
with open('n.csv', 'w', newline='') as f:
csv.writer(f).writerow([10, 20])
with open('n.csv', newline='') as f:
row = next(csv.reader(f))
print(row, row[0] + row[1])
['10', '20'] 1020
The numbers come back as the strings '10' and '20', so + joins them.
Self-check quiz
Each row given by csv.reader is:
Every value is a string, even if it looks like a number.
Which writes several rows in one call?
writerows takes a list of lists.
Why is newline='' passed to open() for a CSV file?
The csv module handles line endings itself.
The default delimiter of the csv writer is:
CSV means comma-separated values; delimiter= can change it.
To add a record to an existing CSV file without losing data, open it with:
CSV is a text file; 'a' appends.
Your score
– / 5
Answer every question to see your score.
One-page revision
import csvwriter and reader objects
newline=''always, when opening a CSV file
w = csv.writer(f)make a writer
writerow(L)one list → one line
writerows(LL)a list of lists → many lines
r = csv.reader(f)make a reader
for row in reach row: a list of strings
next(r)skip the heading row
int(row[2])convert before comparing
delimiter=';'a separator other than the comma
Chapter 19 of 19 · STK
Stack
A stack is the simplest data structure: items go on and come off at one end only, like a pile of plates. Python's list already does both jobs with append() and pop(). A 3-mark stack program (push the items that pass a test, then pop until empty) is in every paper.
STK.01 · Stack
Stack Concept
12-CS
A stack is a linear collection in which items are added and removed at one end only, called the top. The last item added is the first one removed: LIFO, Last In, First Out. Adding is push; removing is pop.
Only the top item can be reached. To get 10 out, 30 and 20 must be popped first.
Overflow: pushing onto a stack that is full (when it has a fixed size). Underflow: popping from an empty stack.
A Python list grows as needed, so a list stack can't overflow, but popping an empty list is an IndexError: the program must check first.
Uses: the undo button and the browser's back button (the last action comes back first), reversing a string, matching brackets, and Python's own record of which function called which.
Exam tip
Assertion "pop() on an empty stack leads to underflow": true. Reason "underflow is when there is no space to add an element": false (that is overflow). "A stack of size 10 receives an 11th push": overflow. The pointer of a stack is the top.
STK.02 · Stack
Operations on Stack
12-CS
Two operations define a stack, push and pop. Programs usually add three helpers: peek (look at the top without removing it), is empty and display.
stack.pop(0) removes the bottom item: that is a queue, not a stack. And stack.insert(0, x) pushes at the wrong end. Always add and remove at the same end: append() and pop().
STK.03 · Stack
Implementation of Stack Using List
12-CS
To implement a stack, write one function per operation, each taking the list (or using a global list) and following the rules above. The practical list asks for exactly this.
Python · push, pop, peek and display
def push(stk, item):
stk.append(item)
def pop(stk):
if stk == []:
print('Underflow: stack is empty')
return None
return stk.pop()
def peek(stk):
if stk == []:
return None
return stk[-1]
def display(stk):
for item in stk[::-1]: # top first
print(item)
s = []
push(s, 'A')
push(s, 'B')
push(s, 'C')
display(s)
print('popped', pop(s), '| top now', peek(s))
pop(s)
pop(s)
pop(s)
Output
C
B
A
popped C | top now B
Underflow: stack is empty
Board pattern: push what passes a test, pop until empty
The question gives a list (or dictionary) and a test. Push goes through the data and appends each item that passes. Pop removes and shows items in a loop while stack != [] (or while stack:), then prints the "empty" message the question asks for.
Python · numbers with 5 or more digits
Nums = [213, 10025, 167, 254923, 14,
1297653, 31498, 386, 92765]
BigNums = []
def PushBig():
for n in Nums:
if len(str(n)) >= 5:
BigNums.append(n)
def PopBig():
while BigNums != []:
print(BigNums.pop())
print('Stack Empty')
PushBig()
print(BigNums)
PopBig()
EventDetails = {'Fair': 450, 'Quiz': 80,
'Sports Day': 1200, 'Debate': 150}
BigEvents = []
def push(events):
for name in events:
if events[name] > 200:
BigEvents.append(name)
push(EventDetails)
print(BigEvents)
print(BigEvents.pop(), BigEvents)
Output
['Fair', 'Sports Day']
Sports Day ['Fair']
Python · reverse a string with a stack
def reverse(text):
stack = []
for ch in text:
stack.append(ch) # push every char
out = ''
while stack:
out += stack.pop() # pop: last first
return out
print(reverse('STACK'))
Output
KCATS
Exam tip
Read whether the question wants the stack passed as a parameter (push_Clr(ClrStack, new_Clr)) or kept in a global list (BigNums = [] outside the functions). In pop, check for empty before popping, and print the exact message given ("Stack Empty", "Underflow").
Chapter practice · STK
Check your understanding
Stack lab
The stack · top at the top
Python shell · the same steps
Predict the output
s = []
for x in [5, 3, 8]:
s.append(x)
s.pop()
s.append(1)
s.append(s.pop() + s.pop())
print(s)
[5, 4]
[5, 3, 8] → pop 8 → push 1: [5, 3, 1] → pop 1 and pop 3, push 1 + 3 = 4: [5, 4].
st = []
for w in 'to be or not'.split():
st.append(w)
print(st.pop(), st.pop(), st)
not or ['to', 'be']
The last word pushed, 'not', comes off first, then 'or'.
Self-check quiz
A stack works on the principle:
Last In, First Out.
Which pointer is associated with a stack?
All work happens at the top.
Popping from an empty stack is called:
Overflow is pushing onto a full stack.
With a list S as a stack (end = top), push is:
append adds at the end, which is the top.
After push 4, push 7, pop, push 2, what is on top?