Python Programming
Class XI CS · Class XI IP · Class XII CS

Python Programming

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
THINKalgorithm BASICStokens · types CONTROLif · loops COLLECTstr list dict REUSEmodules · def KEEPfiles · stack Every example and output on this page was run in Python 3; nothing is typed by hand.
512
2 ** 3 ** 2
** works right to left: 2 ** 9, not 8 ** 2
[::-1]
Reverses a sequence
A negative step walks from the end to the start
1 … 5
randint(1, 5)
Both ends included; randrange(1, 5) stops at 4
None
What append() returns
List methods change the list and return None
Note

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.

    1 ANALYSEwhat is asked 2 ALGORITHMthe plan 3 CODEwrite Python 4 TESTtry test data 5 DEBUGfind + fix a bug was found: fix the code, test again
    The algorithm (filled) is the heart of it: once the steps are right, writing the code is mostly translation.

    Analysing the problem #analysing

    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.

    Developing an algorithm #algorithm

    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.

    1. Read the three marks m1, m2, m3.
    2. Find the total: m1 + m2 + m3.
    3. Find the average: total ÷ 3.
    4. Show the average.

    Coding #coding

    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))
    Output · the user types 18, 15, 20
    Test 1: 18 Test 2: 15 Test 3: 20 Average = 17.67

    Testing #testing

    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.

    Test dataExpectedWhy this test
    18, 15, 2017.67A normal case
    0, 0, 00.0Edge case: all zero
    20, 20, 2020.0Edge case: full marks

    Debugging #debugging

    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.

    Python · the bug
    m1, m2, m3 = 18, 15, 20
    avg = m1 + m2 + m3 / 3      # bug: / runs before +
    print('Average =', avg)
    Output · wrong, not 17.67
    Average = 39.666666666666664
    Python · debugged
    m1, m2, m3 = 18, 15, 20
    avg = (m1 + m2 + m3) / 3   # brackets first
    print('Average =', round(avg, 2))
    Output · test passes
    Average = 17.67
    Exam tip

    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.

    Flowchart #flowchart

    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.

    Start INPUT n s = a+b n > 0 ? TERMINALstart · stop INPUT / OUTPUTread · print PROCESScalculate DECISIONyes / no exits FLOW LINEorder of steps
    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
    STARTINPUT l, barea = l * b PRINT areaSTOP read the two sideswork out the areashow the answer
    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.

    START INPUT n n % 2 == 0 ? PRINT "even" PRINT "odd" STOP Yes No
    One decision, two paths, joined again before Stop.
    Example 3 · nested decisions: largest of three numbers
    STARTINPUT a, b, c a > b ?a > c ?b > c ? big = bbig = cbig = a PRINT bigSTOP YesNo YesNo YesNo
    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.

    START INPUT n s = 0, i = 1 i <= n ? s = s + ii = i + 1 PRINT s STOP YesNo set up: before the loop the loop test the loop body (repeats)
    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 #pseudocode

    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.

    PseudocodeMeansIn Python
    INPUT xRead a valuex = input()
    PRINT xShow a valueprint(x)
    x = expressionWork out and storex = expression
    IF … THEN … ELSE … END IFDecideif …: else:
    WHILE … END WHILERepeat while a condition is truewhile …:
    FOR i = 1 TO n … END FORRepeat a counted number of timesfor 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
    FlowchartPseudocode
    FormA diagram of shapes and arrowsLines of structured English
    Good forSeeing branches and loops at a glanceLong algorithms; close to real code
    DrawbackLarge and slow to draw, hard to changeNo 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.

    MAKE A REPORT CARD 1 · INPUTname, marks 2 · TOTALsum, percent 3 · GRADEif · elif 4 · OUTPUTprint report each part is small enough to write and test on its own
    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)
    a, b, c = 12, 45, 27
    big = a
    if b > big:
        big = b
    if c > big:
        big = c
    print(big)

    Which flowchart symbol shows the step "Is age ≥ 18?"

    A program gives 0 for an average that should be 12.5. Which step of problem solving comes next?

    Self-check quiz

    Which is the correct order of the steps of problem solving?
    An algorithm must be:
    In a flowchart, the parallelogram is used for:
    Which statement about pseudocode is true?
    Breaking a big problem into smaller parts that are solved one by one is called:
    A program runs without any error message but prints a wrong total. Finding and removing this mistake is:
    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.

      Features of Python #features

      FeatureWhat it means
      High-levelWritten in English-like words; you need not think about memory or hardware
      InterpretedRun line by line by an interpreter, with no separate compiling step; it stops at the first error it meets
      Free and open sourceFree to download and use; its source code can be read and improved by anyone
      PortableThe same program runs on Windows, Linux and macOS (platform-independent)
      Simple and readableShort, clear syntax; blocks are shown by indentation, not by braces
      Dynamically typedNo need to declare a variable's type; it comes from the value given to it
      Case-sensitiveTotal and total are two different names
      Rich libraryReady-made modules for maths, files, data, web, games and AI

      One limit: because it is interpreted, Python usually runs slower than compiled languages such as C++.

      Hello world program #hello-world

      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.

      INTERACTIVEthe shell SCRIPTa .py file >>> 2 + 3one statement INTERPRETERruns it now 5shown at once hello.pysaved program INTERPRETERruns all lines OUTPUTonly print()
      The interpreter is the same in both modes. What differs is how much code it gets at once, and whether the code is kept.

      Interactive mode #interactive

      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.

      Python shell
      >>> 2 + 3 5 >>> print('Hello') Hello >>> x = 10 >>> x * 2 20 >>> 'Py' + 'thon' 'Python'

      Script mode #script

      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 modeScript mode
      Code isTyped one statement at a time at >>>Written in a file and saved as .py
      RunsEach statement as soon as Enter is pressedThe whole file, when you run it
      Value of an expressionShown automaticallyShown only with print()
      Saved?No; lost when the shell closesYes; can be edited and run again
      Best forQuick tests and checksReal 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.

      # Program: area of a rectangle length = 12 width = 5 area = length * width if area > 50: print('Large', area) else: print('Small', area) COMMENT · ignored by Python STATEMENTS · run in order EXPRESSION · gives one value HEADER · ends with a colon BLOCK · indented 4 spaces HEADER · else has no test BLOCK · the else part
      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)
      Output
      Large 60

      Indentation #indentation

      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

      Expression #expression

      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.

      Statements #statements

      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.

      Blocks #blocks

      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.

      Comments #comments

      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.

      GroupCharacters
      LettersA–Z and a–z
      Digits0–9
      Special symbols+ - * / % = < > ( ) [ ] { } , . : ; ' " # @ _ \ & | ^ ~ !
      WhitespaceBlank space, tab (\t), newline (\n), carriage return
      Other charactersAll Unicode characters (Python 3 reads source as UTF-8), so strings may hold हिन्दी, ✓ or €
      Python · Unicode and whitespace
      greet = 'नमस्ते'
      print(greet, 'Python')
      print('Tab:\tdone')
      Output
      नमस्ते Python Tab: done
      Exam tip

      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.

      ifmarks>=33: print('Pass') KIOLP IPLP K keyword · I identifier · O operator · L literal · P punctuator
      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.

      Keyword #keyword

      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

      Identifier #identifier

      An identifier is a name given to a variable, function or other object: marks, print, total_2. The rules:

      • It may contain letters, digits and the underscore _ only.
      • It cannot start with a digit.
      • It cannot be a keyword, and cannot contain spaces or symbols such as - @ $ % !.
      • It is case-sensitive (Total ≠ total) and may be of any length.
      NameValid?Reason
      _total✓ validMay start with an underscore
      Total2✓ validA digit is fine after the first character
      For✓ validNot the keyword for: case differs
      2nd✗ invalidStarts with a digit
      my-name✗ invalidHyphen is the minus operator
      roll no✗ invalidContains a space
      $sum✗ invalid$ is not allowed
      for✗ invalidKeyword
      Python shell · what Python says
      >>> _total = 10 >>> Total2 = 20 >>> total = 5 >>> total == Total2 False >>> 2nd = 5 File "<stdin>", line 1 2nd = 5 ^ SyntaxError: invalid decimal literal >>> my-name = 'Riya' File "<stdin>", line 1 my-name = 'Riya' ^ SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='? >>> for = 3 File "<stdin>", line 1 for = 3 ^ SyntaxError: invalid syntax

      Literal #literal

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

      Python shell · literals and their types
      >>> type(25) <class 'int'> >>> type(3.5) <class 'float'> >>> type(2 + 3j) <class 'complex'> >>> type('25') <class 'str'> >>> type(True) <class 'bool'> >>> type(None) <class 'NoneType'> >>> 0b1010 10 >>> 0o17 15 >>> 0xFF 255 >>> 2.5e3 2500.0

      Operator #operator

      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.

      Punctuator #punctuator

      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.

      Variable #variable

      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.

      l-value and r-value 11-CS · 12-CS #l-value-r-value

      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.

      y = x + 2 L-VALUEa name: receives R-VALUEan expression: gives
      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() function #input

      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
      Output · the user types 12 and 30
      First number: 12 Second number: 30 1230 42
      Python · convert as you read
      price = float(input('Price: '))
      qty = int(input('Quantity: '))
      print('Bill =', price * qty)
      Output · the user types 49.5 and 3
      Price: 49.5 Quantity: 3 Bill = 148.5
      Python · simple interest
      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)
      Output · 5000 at 8% for 2 years
      Principal: 5000 Rate % : 8 Years: 2 Simple interest = 800.0 Amount = 5800.0

      print() function #print

      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.

      Python · sep and end
      print('A', 'B', 'C')
      print('A', 'B', 'C', sep='-')
      print('A', 'B', sep='')
      print('Hello', end=' ')
      print('World', end='!\n')
      print()
      print('Total:', 5 + 3, 'items')
      print(10, 20, sep='\n')
      Output
      A B C A-B-C AB Hello World! Total: 8 items 10 20
      Common mistake

      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)
      Num = 4
      num = 9
      print(Num + num, Num * 2)
      a, b = 3, 8
      a, b = b, a
      print(a, b)
      print('A', 'B', sep='*', end='#')
      print('C')

      Which of these are valid identifiers: Roll_No, 1stName, else, _x9, pay-day?

      Self-check quiz

      Python was developed by:
      In which mode does typing 5 + 3 alone show 8?
      The extension of a Python script file is:
      Python marks a block of code by:
      Which is NOT part of Python's character set?
      Which of these is a valid identifier?
      In print("Sum", a + 5), "Sum" is a:
      Which of these is a keyword?
      Which assignment gives an error?
      Which line is a comment in Python?
      The user types 5 for n = input(). What is n * 3?
      What does print(1, 2, 3, sep='') show?
      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
      5 tokenskeyword, identifier, literal, operator, punctuator
      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.

        DATA TYPES NUMBERBOOLEANSEQUENCENONEMAPPING int · floatcomplex bool str · listtuple NoneType dict
        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.

        Integer #integer

        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.

        Python shell
        >>> x = 25 >>> type(x) <class 'int'> >>> 2 ** 100 1267650600228229401496703205376 >>> -7 + 3 -4

        Floating point #float

        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.

        Python shell
        >>> 3.14 3.14 >>> 2.5e3 2500.0 >>> 7 / 2 3.5 >>> 10 / 5 2.0 >>> 0.1 + 0.2 0.30000000000000004

        Complex #complex

        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²).

        Python shell
        >>> z = 3 + 4j >>> type(z) <class 'complex'> >>> z.real 3.0 >>> z.imag 4.0 >>> abs(z) 5.0
        Exam tip

        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.

        Python shell
        >>> type(True) <class 'bool'> >>> 5 > 3 True >>> True + True 2 >>> True == 1 True >>> bool(0) False >>> bool(-3) True >>> bool('') False >>> bool('0') True >>> bool([]) False >>> bool(None) False
        Falsy: bool() gives False
        False, None
        0, 0.0, 0j
        Empty: '' [] () {}
        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)

        String #string

        A string (str) is a sequence of characters in single, double or triple quotes: 'Python', "12A". Strings are immutable. Full chapter: STR.

        List #list

        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.

        Tuple #tuple

        A tuple is like a list in round brackets, (1, 2, 3), but immutable: once made it cannot change. Full chapter: TUP.

        strlisttuple
        Brackets' ' or " "[ ]( )
        ItemsCharacters onlyAny values, mixedAny values, mixed
        Mutable?NoYesNo
        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.

        Dictionary #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.

        Python shell
        >>> d = {'Asha': 91, 'Ravi': 78} >>> type(d) <class 'dict'> >>> d['Ravi'] 78 >>> len(d) 2
        Exam tip

        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.

        IMMUTABLE · int str tuple MUTABLE · list dict x 56 oldnew Lb [1, 2, 3] x = x + 1 makes a new object L.append(3) changes the one object; b = L sees it too
        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.
        ImmutableMutable
        int, float, complex, bool, str, tuplelist, dict (and set)
        Item assignment gives a TypeErrorItems can be changed, added, removed
        Can be a dictionary keyCannot 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.

        Chapter practice · DTY

        Check your understanding

        Predict the output

        print(True + True * 3)
        print(bool('False'), bool(0.0))
        print(type(7 / 7), type(7 // 7))
        print(7 / 7, 7 // 7)
        L = [4, 1]
        print(L.append(2))
        print(L)
        z = 2 - 5j
        print(z.real + z.imag)

        Self-check quiz

        What is the type of 7 / 7?
        Which is a valid complex literal in Python?
        bool(' ') (a single space) gives:
        Which of these is NOT a sequence type?
        The type of None is:
        What does print(L.sort()) show for L = [3, 1]?
        Which is a mutable data type?
        a = [1, 2]; b = a; b.append(3). What is a now?
        Which statement raises an error?
        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.

          OpName17 op 5
          +Addition22
          -Subtraction12
          *Multiplication85
          /Division (always float)3.4
          //Floor division3
          %Modulus (remainder)2
          **Exponent (power)1419857
          Python shell
          >>> 17 + 5 22 >>> 17 - 5 12 >>> 17 * 5 85 >>> 17 / 5 3.4 >>> 17 // 5 3 >>> 17 % 5 2 >>> 2 ** 5 32 >>> 17.0 // 5 3.0 >>> 'ab' + 'cd' 'abcd' >>> 'ab' * 3 'ababab'

          Floor division and modulus

          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.

          Python shell · negatives
          >>> -17 // 5 -4 >>> -17 % 5 3 >>> 17 // -5 -4 >>> 17 % -5 -3
          Python · // and % pick out digits
          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.
          Python shell
          >>> 5 == 5.0 True >>> 7 != 7 False >>> 5 == '5' False >>> 1 < 3 < 5 True >>> 'apple' < 'banana' True >>> 'Z' < 'a' True >>> ord('Z'), ord('a') (90, 97) >>> '10' < '9' True >>> [1, 2] == [1, 2] True
          Exam tip

          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.

          ABA and BA or Bnot A
          TrueTrueTrueTrueFalse
          TrueFalseFalseTrueFalse
          FalseTrueFalseTrueTrue
          FalseFalseFalseFalseTrue
          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 '='?
          ===
          KindAssignmentRelational
          DoesGives a value to a nameTests if two values are equal
          ResultNone shownTrue or False
          Examplea = 5a == 5

          Augmented assignment #augmented

          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?

          abc [1, 2][1, 2] a is b → Trueone object a is c → Falsea == c → True: 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.

          is #is

          x is y is True when x and y are the same object, the same as id(x) == id(y). The usual use is checking for None: if result is None:.

          is not #is-not

          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.

          in #in

          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.

          not in #not-in

          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)
          a = 4
          a += a * 2
          a //= 5
          print(a)
          x, y = 10, 0
          print(x > 5 and y)
          print(y or x)
          print(not x == 10)
          print('5' + '3', '5' * 3, 5 * 3)
          s = 'Kendriya'
          print('end' in s, 'K' not in s)

          Self-check quiz

          What is -13 // 4?
          What is 19 % 4?
          Which is True?
          What does 0 or 'yes' give?
          Which operator is worked out first in not a or b and c?
          After x = 7; x //= 2; x **= 2, x is:
          x++ in Python:
          a = [5]; b = [5]. Which is True?
          For d = {'x': 10}, which gives True?
          'th' in 'Python' gives:
          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 of operators #precedence

            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.

            OrderOperatorsMeaning
            1 (first)( )Brackets
            2**Exponent, right to left
            3+x -xUnary plus and minus
            4* / // %Multiply and divide
            5+ -Add and subtract
            6== != < > <= >= is inRelational, identity, membership
            7notLogical NOT
            8andLogical AND
            9 (last)orLogical 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.

            Associativity #associativity

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

            100 / 10 / 5(100 / 10) / 510.0 / 52.0 2 ** 3 ** 22 ** (3 ** 2)2 ** 9512 LEFT TO RIGHT · * / // % + - RIGHT TO LEFT · ** only not 50.0not 64
            Associativity puts the invisible brackets in: on the left for /, on the right for **. Brackets you write yourself always win.
            OperatorsAssociativityExample
            **Right to left2 ** 3 ** 2 = 2 ** 9 = 512
            * / // %Left to right100 / 10 / 5 = 10.0 / 5 = 2.0
            + -Left to right7 - 3 - 2 = 4 - 2 = 2
            ComparisonsChained1 < x < 5 means 1 < x and x < 5
            Python shell · the brackets Python puts in
            >>> 100 / 10 / 5 2.0 >>> (100 / 10) / 5 2.0 >>> 100 / (10 / 5) 50.0 >>> 7 - 3 - 2 2 >>> 2 ** 3 ** 2 512 >>> 2 ** (3 ** 2) 512 >>> (2 ** 3) ** 2 64

            Evaluation of expression #evaluation

            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:

            10 - 3 ** 2 ** 2 + 144 / 12 10 - 3 ** 4 + 144 / 12 10 - 81 + 144 / 12 10 - 81 + 12.0 -71 + 12.0 -59.0 1 ** first, and right to left 2 the remaining ** 3 / is above + and - 4 + and - go left to right 5 the last operator a float, because / was used
            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)
            Output
            4 81 12.0 -71 -59.0 -59.0
            Python shell · past board expressions
            >>> 2 // 18 % 4 ** 2 + 3 3 >>> 4 + 2 ** 3 ** 2 / 2 260.0 >>> 10 - 3 ** 2 ** 2 + 144 / 12 -59.0 >>> -2 ** 2 -4 >>> (-2) ** 2 4 >>> 5 + 3 > 7 and not 2 == 3 True
            Exam tip

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

            Explicit conversion #explicit

            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'

            Implicit conversion #implicit

            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.

            Python shell
            >>> 5 + 2.0 7.0 >>> True + 4 5 >>> 7 / 7 1.0 >>> 3 * 1.0 3.0 >>> 'Age: ' + 15 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str >>> 'Age: ' + str(15) 'Age: 15'
            ExplicitImplicit
            Done byThe programmer, with int(), float(), str() …Python, automatically
            Exampleint('25') + 5 → 305 + 2.0 → 7.0
            Can lose data?Yes: int(3.99) → 3No: always to the wider type
            Exam tip

            "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)
            print(10 - 4 / 2 ** 2 * 3)
            x = 15
            print(x > 10 and x % 2 == 0 or x // 4 == 3)
            print(int('7') + float('2.5'), str(7) * 2)

            Self-check quiz

            What does print(2 ** 2 ** 3) show?
            Which operator has the lowest precedence?
            What is -3 ** 2?
            What is int(-7.8)?
            x = 4 + 2.5 is an example of:
            Which gives a ValueError?
            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.

              CODE CHECK + RUN OUTPUT SYNTAX ERRORfound before it runs RUNTIME ERRORstops at the bad line LOGICAL ERRORruns; answer is wrong
              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.

              Syntax error #syntax

              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

              Logical error #logical

              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)
              Output
              Sum of 1 to 10 = 55

              Runtime error #runtime

              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'
              ErrorRaised when
              ZeroDivisionErrorDividing (/, //, %) by zero
              NameErrorUsing a name that has not been given a value
              TypeErrorAn operation on the wrong type: '5' + 5, s[0] = 'x'
              ValueErrorThe type is right but the value is not: int('five')
              IndexErrorAn index outside the sequence
              KeyErrorA key that is not in the dictionary
              ModuleNotFoundErrorImporting 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 '='?
              LineErrorKindCorrection
              while(n < 0):Loop never runs for a positive numberLogicalwhile n > 0:
              dig==n%10== compares; it does not storeLogicaldig = n % 10
              if(temp=rev)= instead of ==, and no colonSyntaxif 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])
              age = 15
              print('Age: ' + age)

              Name the kind of error: avg = (a + b) / 3 in a program meant to average two numbers.

              Name the kind of error: for i in range(5) print(i)

              Self-check quiz

              An error that Python finds before running even the first line is a:
              A program runs to the end but prints a wrong answer. The error is:
              int('12a') raises:
              Which is a runtime error?
              Which correction is right for if x = 10?
              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).

                Types of statements #statement-types

                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.

                STATEMENTS EMPTYpass SIMPLEx = 5 · print(x) COMPOUNDheader: + block CONDITIONALif, if-else LOOPINGfor, while does nothing; fills aplace that needs a statementone line, run once,top to bottom
                A compound statement contains other statements in its indented block, simple or compound, which is how ifs and loops can be nested.
                TypeWhat it isExamples
                Empty statementA statement that does nothing. Used where Python's grammar needs a statement but there is nothing to do yet, such as an empty blockpass
                Simple statementA single line that does one thingx = 5, print(x), n = int(input()), import math, break, continue
                Compound statementA header line ending in a colon, plus an indented block of other statementsif, 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

                SEQUENTIAL CONDITIONAL ITERATIVE STEP 1STEP 2STEP 3 test? else part if part NEXT test? loop body NEXT Yes No Yes No
                The test (filled diamond) is what makes flow conditional or iterative. In a loop, the "Yes" path leads back to the same test.

                Sequential flow #sequential

                In sequential flow statements run one after another, in the order written, each exactly once. It is the default.

                Python · top to bottom
                length = 8
                width = 5
                area = length * width
                print('Area =', area)
                Output
                Area = 40

                Conditional flow #conditional

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

                Iterative flow #iterative

                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.

                if #if

                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.

                marks = 45marks >= 33 ? PRINT 'Pass'PRINT 'Done' YesNo if blocknext 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)
                Output · the user types −7
                Enter a number: -7 Absolute value: 7

                if-else #if-else

                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.

                n = 35n % 5 == 0 ? PRINT 'yes'PRINT 'no'next statement YesNo
                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')
                Output · the user types 35
                Enter a number: 35 35 is divisible by 5

                if-elif-else #if-elif-else

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

                m >= 90 ? m >= 75 ? m >= 60 ? grade = 'A' grade = 'B' grade = 'C' grade = 'D' PRINT grade else YesYesYes NoNoNo
                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.

                Flowchart 11-CS · 12-CS #flowchart

                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.

                START INPUT n f = 1, i = 1 i <= n ? f = f * ii = i + 1 PRINT f STOP YesNo set up: before the loop the loop test the loop body (repeats)
                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 loop #for

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

                for x in [3, 6, 9]:items left? x = next itemprint(x * 2)after the loop YesNo x = 3 → prints 6x = 6 → prints 12x = 9 → prints 18none left: loop ends
                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=' ')
                Output
                K V 6 12 18

                range() function #range

                range() makes a sequence of integers, most often for a for loop. It counts from start up to, but never including, stop, in jumps of step.

                FormGivesExample
                range(stop)0, 1, … stop − 1range(5) → 0 1 2 3 4
                range(start, stop)start … stop − 1range(2, 8) → 2 … 7
                range(start, stop, step)start, start + step, … before stoprange(1, 10, 3) → 1 4 7
                Negative stepCounts down; stop is still left outrange(10, 0, -2) → 10 … 2
                Python shell
                >>> list(range(5)) [0, 1, 2, 3, 4] >>> list(range(2, 8)) [2, 3, 4, 5, 6, 7] >>> list(range(1, 10, 3)) [1, 4, 7] >>> list(range(10, 0, -2)) [10, 8, 6, 4, 2] >>> list(range(5, 1)) [] >>> len(range(7, 40, 6)) 6
                Python · a board question
                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 loop #while

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

                n = 1n <= 5 ? print(n)n += 1after the loop YesNo n = 1 → prints 1…n = 5 → prints 5n = 6: test is False
                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)
                Output · the user types 5274
                Number: 5274 Sum of digits = 18
                forwhile
                RepeatsOnce for each item of a sequenceAs long as a condition is True
                Number of timesKnown in advanceNot always known
                Loop variableUpdated automaticallyMust be updated in the body
                Typical useGo through a list; count with range()Digits of a number; read until "stop"

                Infinite loop #infinite-loop

                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.

                n <= 5 ?print(n)n += 1 (missing) n is still 1, so the test is True again, and again, for ever YesNo: never taken
                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 causeExampleFix
                The update is missingwhile n <= 5: with no n += 1Change the loop variable in the body
                The update goes the wrong waywhile n <= 5: with n -= 1Move towards the end condition
                The update jumps over the end valuewhile n != 0: with n = 10 and n -= 3Test with > or <, not !=
                The update is outside the loopn += 1 written without indentation, after the loopIndent it into the loop's block
                The condition can never be Falsewhile True: with no breakAdd 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 and continue 11-CS · 12-CS #break-continue

                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.

                NEXT ROUNDitem or test LOOP BODY… continue …… break … AFTER LOOPnext statement break continue, or end of the body: go to the next round no items left, or the test is False: the loop ends
                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')
                Output
                29 is prime 91 is composite, divisor 7

                Nested loops 11-CS · 12-CS #nested

                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.

                1234246836912 j = 1j = 2j = 3j = 4 i = 1i = 2i = 3 inner loop: 4 turns, thenprint() ends the rowi = 2, j = 3 → prints 6last row; outer loop ends 3 outer turns × 4 inner turns = 12 runs of the inner body
                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()
                Output
                1 2 3 4 2 4 6 8 3 6 9 12

                Pattern generation 11-CS · 12-CS #patterns

                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()
                A AB ABC ABCD ABCDE

                Series summation 11-CS · 12-CS #series

                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)
                Output · x = 2, n = 4
                x: 2 n: 4 1 + x + ... + x^n = 31 1 - x + ... x^n = 11
                Python · division and factorial terms
                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.

                Factorial #factorial

                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='-')
                i = 0
                while i < 5:
                    i += 1
                    if i == 3:
                        continue
                    print(i, end=' ')
                L = [3, 10, 6, 13]
                for I in L:
                    for J in range(I % 2, 5):
                        print(J, '#', end='')
                    print()
                marks = 95
                if marks >= 33:
                    print('D')
                elif marks >= 90:
                    print('A')
                else:
                    print('Fail')
                for i in range(1, 6):
                    for j in range(1, i):
                        print(j % 2, end=' ')
                    print()
                x = 10
                while x > 0:
                    x -= 3
                    print(x, end=' ')

                Self-check quiz

                Which is the empty statement in Python?
                Which statement gives iterative flow?
                How many times does for i in range(2, 20, 4): run?
                list(range(5, 0, -1)) is:
                In an if-elif-else chain, how many blocks can run?
                What does continue do?
                "A break in an inner loop ends all the loops at once." This is:
                To find a factorial, the product variable should start at:
                Which loop never ends?
                How many times does the body of while x < 10: run if x starts at 15?
                With for i in range(3): outside and for j in range(4): inside, the inner body runs:
                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.

                  Indexing #indexing

                  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.

                  PYTHON 012345 -6-5-4-3-2-1 s[i]s[-i]
                  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.

                  Concatenation #concatenation

                  Concatenation with + joins two strings end to end. Both sides must be strings; convert a number with str() first.

                  Python shell
                  >>> 'Good' + ' ' + 'Morning' 'Good Morning' >>> 'Class ' + str(11) 'Class 11' >>> 'Class ' + 11 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate str (not "int") to str

                  Repetition #repetition

                  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'

                  Membership #membership

                  in and not in test whether one string occurs anywhere inside another, matching case exactly. The empty string is in every string.

                  Python shell
                  >>> 'a' in 'India' True >>> 'IND' in 'India' False >>> 'dia' not in 'India' False >>> '' in 'India' True

                  Slicing #slicing

                  A slice s[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".

                  COMPUTER COMPUTER 012345678 -8-7-6-5-4-3-2-1 01234567 s[2:6] → 'MPUT': cut at 2 and at 6 s[-6:-2] makes the same two cuts s[::-2] → 'RTPO': from index 7, back 2 each time cutcutindex
                  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.
                  Python shell · start and stop
                  >>> s = 'COMPUTER' >>> s[2:6] 'MPUT' >>> s[:4] 'COMP' >>> s[4:] 'UTER' >>> s[:] 'COMPUTER' >>> s[-3:] 'TER' >>> s[-6:-2] 'MPUT' >>> s[2:100] 'MPUTER' >>> s[6:2] ''
                  Python shell · with a step
                  >>> s = 'COMPUTER' >>> s[::2] 'CMUE' >>> s[1::3] 'OUR' >>> s[::-1] 'RETUPMOC' >>> s[::-2] 'RTPO' >>> s[6:2:-1] 'ETUP' >>> s[-1:-4:-1] 'RET'
                  • 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().

                  GroupMethodsReturn
                  Lengthlen(s)int
                  Change casecapitalize() title() lower() upper()new str
                  Searchcount() find() index() startswith() endswith()int / bool
                  Test (is…)isalnum() isalpha() isdigit() islower() isupper() isspace()bool
                  Trimlstrip() rstrip() strip()new str
                  Change and splitreplace() join() partition() split()str / tuple / list

                  Length

                  01234567Hi␣therelen('Hi there') → 8: the space is a character too
                  Every character counts, spaces and punctuation included.

                  len(s) #len

                  The number of characters, spaces included.

                  >>> len('Python') 6 >>> len('Hi there') 8 >>> len('') 0

                  Changing case

                  shello␣WORLDthe originals.capitalize()Hello␣world6 changeds.title()Hello␣World5 changeds.lower()hello␣world5 changeds.upper()HELLO␣WORLD5 changed
                  The same string through all four case methods; the filled letters are the ones that changed. Digits and symbols are never changed.

                  s.capitalize() #capitalize

                  First character upper case, all the rest lower.

                  >>> 'hello WORLD'.capitalize() 'Hello world' >>> '2nd term'.capitalize() '2nd term'

                  s.title() #title

                  Each word starts with a capital; a "word" restarts after any non-letter, even '.

                  >>> 'hello world'.title() 'Hello World' >>> "it's kv-2".title() "It'S Kv-2"

                  s.lower() #lower

                  Every letter in lower case; digits and symbols unchanged.

                  >>> 'PyThOn 3.12'.lower() 'python 3.12'

                  s.upper() #upper

                  Every letter in upper case.

                  >>> 'PyThOn 3.12'.upper() 'PYTHON 3.12'

                  Searching

                  012345bananafind('an') → 1find('an', 2) → 3count('a') → 3 (filled boxes)startswith('ba') → Trueendswith('na') → Truecount('an') → 2find('x') → -1index('x') → ValueError
                  find() and index() give the first position where the text starts; the optional second argument says where to start looking.

                  s.count(sub[, start]) #count

                  How many times sub occurs, without overlapping; optionally from index start.

                  >>> s = 'banana' >>> s.count('a') 3 >>> s.count('an') 2 >>> s.count('a', 2) 2 >>> s.count('x') 0

                  s.find(sub[, start]) #find

                  Index of the first occurrence, or −1 if it is not there. Case matters.

                  >>> s = 'banana' >>> s.find('an') 1 >>> s.find('an', 2) 3 >>> s.find('x') -1 >>> 'TariffWar'.find('war') -1

                  s.index(sub) #index

                  Like find(), but a missing sub is a ValueError.

                  >>> s = 'banana' >>> s.index('n') 2 >>> s.index('x') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found

                  s.endswith(sub) #endswith

                  True if s ends with sub.

                  >>> 'report.pdf'.endswith('.pdf') True >>> 'report.pdf'.endswith('PDF') False

                  s.startswith(sub) #startswith

                  True if s begins with sub.

                  >>> 'Mr. Rao'.startswith('Mr') True >>> 'Mr. Rao'.startswith('Mrs') False

                  Testing characters

                  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)
                  Output · yes = True, - = False
                  string alnum alpha digit lower upper space 'Class12' yes - - - - - 'Python' yes yes - - - - '2025' yes - yes - - - 'hello' yes yes - yes - - 'KV NO. 1' - - - - yes - ' ' - - - - - yes 'a b' - - - yes - - '' - - - - - -

                  s.isalnum() #isalnum

                  True if every character is a letter or digit, and s is not empty.

                  >>> 'Class12'.isalnum() True >>> 'Class 12'.isalnum() False >>> ''.isalnum() False

                  s.isalpha() #isalpha

                  True if every character is a letter.

                  >>> 'Python'.isalpha() True >>> 'Python3'.isalpha() False

                  s.isdigit() #isdigit

                  True if every character is a digit, so a sign or a point fails.

                  >>> '2025'.isdigit() True >>> '-5'.isdigit() False >>> '3.5'.isdigit() False

                  s.islower() #islower

                  True if it has at least one letter and all its letters are lower case.

                  >>> 'hello 123'.islower() True >>> 'Hello'.islower() False >>> '123'.islower() False

                  s.isupper() #isupper

                  True if it has a letter and all its letters are upper case.

                  >>> 'KV NO. 1'.isupper() True >>> 'KVs'.isupper() False

                  s.isspace() #isspace

                  True if s is not empty and all whitespace (space, tab, newline).

                  >>> ' '.isspace() True >>> '\t\n'.isspace() True >>> ' a '.isspace() False >>> ''.isspace() False

                  Trimming

                  s***Park***s.lstrip('*')***Park***→ 'Park***'s.rstrip('*')***Park***→ '***Park's.strip('*')***Park***→ 'Park'
                  Trimming removes characters only from the ends: the stars are removed until a character that is not a star is reached. The middle is never touched.

                  s.lstrip([chars]) #lstrip

                  Removes leading (left) whitespace, or the given characters.

                  >>> ' hi '.lstrip() 'hi ' >>> '***Park***'.lstrip('*') 'Park***'

                  s.rstrip([chars]) #rstrip

                  Removes trailing (right) whitespace, or the given characters.

                  >>> ' hi '.rstrip() ' hi' >>> '***Park***'.rstrip('*') '***Park'

                  s.strip([chars]) #strip

                  Removes from both ends. chars is a set: any of them, in any order.

                  >>> ' hi '.strip() 'hi' >>> '***Park***'.strip('*') 'Park' >>> 'xyhiyx'.strip('xy') 'hi'

                  Changing and splitting

                  'banana'.replace('a', 'o')'bonono'str'a,b,,c'.split(',')'a''b''''c'list of 4'Hello World Hi'.partition(' ')'Hello'' ''World Hi'tuple of 3'-'.join(['2025', '11', '19'])'2025-11-19'str
                  Look at the type of each result: replace and join give a string, split a list, partition a tuple of exactly 3.

                  s.replace(old, new[, n]) #replace

                  Every old becomes new; with n, only the first n.

                  >>> 'copyPYTHON'.replace('PY', '#') 'copy#THON' >>> 'banana'.replace('a', 'o') 'bonono' >>> 'banana'.replace('a', 'o', 2) 'bonona'

                  sep.join(items) #join

                  Joins strings with sep between them. Every item must be a string.

                  >>> '-'.join(['2025', '11', '19']) '2025-11-19' >>> '*'.join('KV') 'K*V' >>> ''.join(['a', 'b', 'c']) 'abc' >>> ' '.join([1, 2]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sequence item 0: expected str instance, int found

                  s.partition(sep) #partition

                  Splits at the first sep into a tuple of 3: before, sep, after.

                  >>> 'Hello World Hi'.partition(' ') ('Hello', ' ', 'World Hi') >>> 'abc'.partition('x') ('abc', '', '')

                  s.split([sep]) #split

                  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 confusedDifference
                  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])
                  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)
                  text = 'We shall overcome some day'
                  print(text.partition('me'))
                  print(text.split('me'))
                  msg = 'Buildathon Hackathon'
                  print(msg.replace('th', 'j'))
                  print(msg.index('a'))
                  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'))
                  st = 'CBSE 2022-2023'
                  print(len(st.split('2')))
                  print(st.split('2'))

                  Self-check quiz

                  For s = 'KENDRIYA', what is s[-3]?
                  'Python'[1:4] is:
                  print('now-', 'Smile' * -2) shows:
                  'TariffWar'.find('war') gives:
                  Which method returns a tuple?
                  Which gives True?
                  After s = 'kv'; s.upper(), s is:
                  '*'.join('ABC') is:
                  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.

                    Creating and initializing #creating

                    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.

                    Python shell
                    >>> L1 = [10, 20, 30] >>> L2 = ['Asha', 17, 88.5, True] >>> L2 ['Asha', 17, 88.5, True] >>> [] [] >>> list('KV') ['K', 'V'] >>> list(range(1, 6)) [1, 2, 3, 4, 5] >>> [0] * 5 [0, 0, 0, 0, 0]
                    Python · read n numbers into a list
                    L = []
                    n = int(input('How many numbers? '))
                    for i in range(n):
                        L.append(int(input('Number: ')))
                    print('The list:', L)
                    Output · the user types 3, then 12, 7, 25
                    How many numbers? 3 Number: 12 Number: 7 Number: 25 The list: [12, 7, 25]

                    Indexing #indexing

                    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

                    Nested list 11-CS · 12-CS #nested

                    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.

                    123456 [0][1][2] M[0]M[1] M[1][2] is 6: row 1 first, then item 2 of it
                    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).
                    Python shell
                    >>> M = [[1, 2, 3], [4, 5, 6]] >>> M[1] [4, 5, 6] >>> M[1][2] 6 >>> len(M), len(M[0]) (2, 3) >>> M[0][1] = 20 >>> M [[1, 20, 3], [4, 5, 6]]
                    Python · visit every item
                    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.

                    Concatenation #concatenation

                    L1 + L2 joins two lists into a new one. Both sides must be lists; to add one value, wrap it: L + [3].

                    Python shell
                    >>> [1, 2] + [3, 4] [1, 2, 3, 4] >>> ['a'] + ['b', 'c'] ['a', 'b', 'c'] >>> [1, 2] + 3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can only concatenate list (not "int") to list

                    Repetition #repetition

                    L * n repeats the items n times; handy for making a list of zeros.

                    Python shell
                    >>> [0] * 4 [0, 0, 0, 0] >>> ['a', 'b'] * 2 ['a', 'b', 'a', 'b'] >>> [1, 2] * 0 []

                    Membership #membership

                    x in L is True if x equals one of the items. Unlike strings, it does not look inside items: 'av' in ['Ravi'] is False.

                    Python shell
                    >>> 3 in [1, 2, 3] True >>> 'Ravi' in ['Asha', 'Ravi'] True >>> 'av' in ['Ravi'] False >>> [1, 2] in [[1, 2], 3] True

                    Slicing #slicing

                    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.

                    Python shell
                    >>> L = [10, 20, 30, 40, 50, 60] >>> L[1:4] [20, 30, 40] >>> L[:3] [10, 20, 30] >>> L[::2] [10, 30, 50] >>> L[::-1] [60, 50, 40, 30, 20, 10] >>> L[-2:] [50, 60] >>> L[1:4] = ['a', 'b'] >>> L [10, 'a', 'b', 50, 60]

                    Copying a list

                    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])
                    Output
                    78 91 65 Student 1 : 78 Student 2 : 91 Student 3 : 65
                    Python · changing items needs the index
                    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('abc')'a''b''c'a new listlen([10, 20, 30])102030→ 3len([[1, 2], [3]])[1, 2][3]→ 2 (inner list = 1)
                    list() turns any sequence into a list, one item per element; len() counts the items at the top level only.

                    len(L) #len

                    Number of items; a nested list counts as one.

                    >>> len([10, 20, 30]) 3 >>> len([]) 0 >>> len([[1, 2], [3]]) 2

                    list(seq) #list

                    A new list from any sequence; from a dictionary, its keys.

                    >>> list('abc') ['a', 'b', 'c'] >>> list((1, 2)) [1, 2] >>> list(range(3)) [0, 1, 2] >>> list({'a': 1, 'b': 2}) ['a', 'b']

                    Adding items

                    L.append([3, 4])L.extend([3, 4])L.insert(1, 9) 12[3, 4] 1234 192 3 items: one is a list4 items3 items: 9 at index 1 each row starts from L = [1, 2]; the filled boxes are what was added
                    append adds its argument as one item, whatever it is; extend adds each item of its argument; insert adds one item at a chosen index.

                    L.append(x) #append

                    Adds x as one item at the end. Returns None.

                    >>> L = [1, 2] >>> L.append(3) >>> L.append([4, 5]) >>> L [1, 2, 3, [4, 5]]

                    L.extend(seq) #extend

                    Adds every item of seq at the end. Returns None.

                    >>> L = [1, 2] >>> L.extend([3, 4]) >>> L.extend('ab') >>> L [1, 2, 3, 4, 'a', 'b']

                    L.insert(i, x) #insert

                    Puts x before index i. Past the end, it goes last; −1 means before the last item.

                    >>> L = ['a', 'c'] >>> L.insert(1, 'b') >>> L.insert(10, 'z') >>> L.insert(-1, 'y') >>> L ['a', 'b', 'c', 'y', 'z']

                    Finding items

                    012341020302010index(20) → 1: the first onecount(20) → 2: the filled boxescount(10) → 2count(99) → 0index(30) → 2index(99) → ValueError
                    count() looks at every item; index() stops at the first match. Both compare whole items, not parts of them.

                    L.count(x) #count

                    How many items equal x.

                    >>> L = [1, 2, 1, 3, 1] >>> L.count(1) 3 >>> L.count(5) 0

                    L.index(x) #index

                    Index of the first x; ValueError if x is absent.

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

                    L5358the list each row starts fromL.remove(5)5358by value: first 5 only; returns NoneL.pop()5358the last item; returns 8L.pop(1)5358by index: index 1 goes; returns 3
                    remove() is told what to delete; pop() is told where. Only pop() gives the deleted item back.

                    L.remove(x) #remove

                    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

                    L.pop([i]) #pop

                    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

                    L301020the list each row starts fromL.reverse()201030changes L; returns NoneL.sort()102030changes L; returns NoneL.sort(reverse=True)302010changes L; returns Nonesorted(L)102030a NEW list; L stays [30, 10, 20]
                    reverse() and sort() rearrange the list itself and return None; sorted() leaves it alone and returns a new, sorted list.

                    L.reverse() #reverse

                    Reverses the list in place. Returns None.

                    >>> L = [1, 2, 3] >>> L.reverse() >>> L [3, 2, 1] >>> print(L.reverse()) None

                    L.sort([reverse=True]) #sort

                    Sorts in place, ascending, or descending with reverse=True. Capitals sort before small letters.

                    >>> L = [30, 10, 20] >>> L.sort() >>> L [10, 20, 30] >>> L.sort(reverse=True) >>> L [30, 20, 10] >>> W = ['bat', 'Apple', 'cat'] >>> W.sort() >>> W ['Apple', 'bat', 'cat']

                    sorted(seq) 11-CS · 12-CS #sorted

                    Returns a new sorted list; the original is unchanged.

                    >>> L = [30, 10, 20] >>> sorted(L) [10, 20, 30] >>> L [30, 10, 20] >>> sorted(L, reverse=True) [30, 20, 10] >>> sorted('kvs') ['k', 's', 'v']

                    Summarising

                    492max → 9min → 2L = [4, 9, 2]sum(L) → 4 + 9 + 2 = 15max(['pear', 'apple', 'fig'])→ 'pear': last alphabeticallysum([1.5, 2]) → 3.5sum(['a', 'b']) → TypeError
                    min() and max() work on any items that can be compared; sum() only on numbers.

                    min(L) #min

                    The smallest item; items must be comparable.

                    >>> min([4, 9, 2]) 2 >>> min(['pear', 'apple']) 'apple' >>> min([]) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: min() iterable argument is empty

                    max(L) #max

                    The largest item; for strings, by character code.

                    >>> max([4, 9, 2]) 9 >>> max('Python') 'y'

                    sum(L) #sum

                    Total of the items; numbers only.

                    >>> 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 confusedDifference
                    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).

                    Maximum, minimum and mean #max-min-mean

                    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

                    Frequency count #frequency

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

                    Chapter practice · LST

                    Check your understanding

                    Predict the output

                    P = [1, 9, 4, 6]
                    P.insert(2, 3)
                    P.extend([8, 5])
                    print(P)
                    print(P.append([2, 3]))
                    print(P[::2])
                    cities = ['Delhi', 'Kolkata', 'Chennai',
                              'Mumbai', 'Pune', 'Agra']
                    result = []
                    for city in cities:
                        if len(city) % 2 == 0:
                            result.append(city[-2:].upper())
                    print(result)
                    L = ['Kendriya', 'Vidyalaya', 'Sangathan']
                    print(L[1][0] + 2 * L[2][-1])
                    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='#')
                    lst = [1, 2, 3, 4]
                    for i in lst:
                        lst.remove(i)
                    print(lst)
                    a = [1, 2]
                    b = a
                    c = a[:]
                    a += [3]
                    print(b, c)

                    Self-check quiz

                    For L = [10, 20, 30, 40], L[-3:] is:
                    After L = [1, 2]; L.append([3, 4]), len(L) is:
                    Which removes an item by its index and returns it?
                    L = [3, 1, 2]; print(L.sort()) shows:
                    [1, 2] * 2 + [3] is:
                    For M = [[1, 2], [3, 4], [5, 6]], M[2][0] is:
                    L = ['a', 'b']; L.insert(0, 'z') gives:
                    In linear search on a list of n items, the most comparisons needed is:
                    Which makes an independent copy of list a?
                    sum([2, 4, 6]) / len([2, 4, 6]) is:
                    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.

                      Python shell
                      >>> t = (10, 20, 30) >>> t (10, 20, 30) >>> type((5)) <class 'int'> >>> type((5,)) <class 'tuple'> >>> t2 = 1, 2, 3 >>> t2 (1, 2, 3) >>> tuple('ab') ('a', 'b') >>> () ()

                      Indexing #indexing

                      Indexes work as for strings and lists: 0 to len − 1, or −1 to −len. Reading t[i] is fine; assigning to it is a TypeError.

                      Python shell
                      >>> t = ('a', 'b', 'c', 'd') >>> t[1], t[-1] ('b', 'd') >>> t[1] = 'z' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment

                      Nested tuple #nested

                      A tuple can hold other tuples (or lists, or strings). A second index reaches inside the inner item, as with nested lists.

                      Python shell
                      >>> T = ((1, 2), (3, 4), 'xy') >>> T[1] (3, 4) >>> T[1][0] 3 >>> T[2][1] 'y' >>> len(T) 3

                      Tuple assignment #tuple-assignment

                      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.

                      102030abc PACKEDone tuple UNPACKEDthree names 3 items → 3 names;any other count isa ValueError a, b, c = (10, 20, 30)
                      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)
                      ListTuple
                      Brackets[1, 2](1, 2), or just 1, 2
                      Mutable?Yes: items can changeNo: fixed once made
                      MethodsMany (append, sort, pop …)Only count() and index()
                      Dictionary key?NoYes (if its items are immutable)
                      Use forData that grows or changesFixed 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.

                      Concatenation #concatenation

                      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)
                      Output
                      (1, 2, 3, 4) (1, 2, 3) False

                      Repetition #repetition

                      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.

                      Python shell
                      >>> ('a',) * 3 ('a', 'a', 'a') >>> (1, 2) * 2 (1, 2, 1, 2) >>> tup = (5,) >>> [tup] * 3 [(5,), (5,), (5,)]

                      Membership #membership

                      x in t and x not in t test whether x equals one of the items.

                      Python shell
                      >>> 3 in (1, 2, 3) True >>> 'x' not in ('a', 'b') True

                      Slicing #slicing

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

                      Python shell
                      >>> t = (10, 20, 30, 40, 50, 60, 70, 80, 90) >>> t[2:5] (30, 40, 50) >>> t[::3] (10, 40, 70) >>> t[-2:-5] () >>> t[-2:-5:-1] (80, 70, 60)
                      Exam tip

                      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([1, 2])12a tuple of 2tuple('hi')'h''i'one item per characterlen(((1, 2), 3))(1, 2)3→ 2 (inner tuple = 1)
                      tuple() turns any sequence into a tuple; len() counts the items at the top level only.

                      len(t) #len

                      Number of items; an inner tuple counts as one.

                      >>> len((1, 2, 3)) 3 >>> len(((1, 2), 3)) 2

                      tuple(seq) #tuple

                      A new tuple from any sequence.

                      >>> tuple([1, 2]) (1, 2) >>> tuple('hi') ('h', 'i') >>> tuple(range(3)) (0, 1, 2)

                      Finding items

                      01231211index(2) → 1count(1) → 3: the filled boxest.index(1) → 0t.count(7) → 0t.index(9) → ValueError
                      The two tuple methods. Both only read the tuple, which is why tuples are allowed to have them.

                      t.count(x) #count

                      How many items equal x.

                      >>> t = (1, 2, 1, 1) >>> t.count(1) 3 >>> t.count(7) 0

                      t.index(x) #index

                      Index of the first x; ValueError if absent.

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

                      t(3, 1, 2)the tuplesorted(t)[1, 2, 3]a LIST, not a tupletuple(sorted(t))(1, 2, 3)back to a tuplet.sort()AttributeErrora tuple can't be changed
                      A tuple can't be sorted in place, so there is no t.sort(). sorted() reads it and returns a new list.

                      sorted(t) #sorted

                      Returns a sorted list, not a tuple. Wrap it in tuple() if needed.

                      >>> sorted((3, 1, 2)) [1, 2, 3] >>> tuple(sorted((3, 1, 2))) (1, 2, 3)

                      Summarising

                      t = (4, 9, 2)492max → 9min → 2sum(t) → 4 + 9 + 2 = 15min(('kv', 'KV')) → 'KV'capitals sort firstsum(('a', 'b')) → TypeError
                      The same built-in functions as for lists; sum() needs numbers.

                      min(t) #min

                      The smallest item. 'KV' < 'kv' because capitals come first.

                      >>> min((4, 9, 2)) 2 >>> min(('kv', 'KV')) 'KV'

                      max(t) #max

                      The largest item.

                      >>> max((4, 9, 2)) 9

                      sum(t) #sum

                      Total of the numbers.

                      >>> sum((4, 9, 2)) 15
                      Exam tip

                      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,).

                      Maximum, minimum and mean #max-min-mean

                      Python · read a tuple, then summarise
                      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

                      Frequency count #frequency

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

                      Chapter practice · TUP

                      Check your understanding

                      Predict the output

                      tuple1 = (1, 2, 3)
                      tuple2 = tuple1
                      tuple1 += (4,)
                      print(tuple1 == tuple2)
                      tup1 = (10, 20, 30, 40, 50, 60, 70, 80, 90)
                      print(tup1[-2:-5])
                      print(tup1[-5:-2])
                      t = (5)
                      u = (5,)
                      print(t * 2, u * 2)
                      tup = (5,)
                      result = [tup] * 3
                      print(result)
                      t = (1, 2, 3)
                      a, b, c = t
                      print(a + c, b * 2, t[::-1])

                      Self-check quiz

                      Which of these is a tuple?
                      For t = (4, 8, 12), which statement raises an error?
                      How many methods does a tuple have (besides the built-in functions)?
                      sorted((5, 2, 9)) returns:
                      After a, b = 3, 7 and a, b = b, a + b, the values are:
                      x, y = (1, 2, 3) gives:
                      (1, 2) * 2 + (3,) is:
                      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.

                        Key-value pair #key-value

                        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.

                        'Asha''Ravi''Meena'917885 KEYSVALUES marks['Ravi'] unique, immutable→ 78any type
                        A lookup goes straight to the key, however large the dictionary. A key that is not there raises KeyError.
                        Python · a board question: a key written twice
                        drs = {'Kerala': 3, 'Karnataka': 5,
                               'Goa': 4, 'Kerala': 1}
                        print(drs)
                        Output
                        {'Kerala': 1, 'Karnataka': 5, 'Goa': 4}

                        Creating and initializing #creating

                        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.

                        Python shell
                        >>> d = {'Asha': 91, 'Ravi': 78} >>> d {'Asha': 91, 'Ravi': 78} >>> {} {} >>> dict(name='Asha', age=16) {'name': 'Asha', 'age': 16} >>> dict([('a', 1), ('b', 2)]) {'a': 1, 'b': 2} >>> {1: 'one', (2, 3): 'pair'} {1: 'one', (2, 3): 'pair'} >>> {[1, 2]: 'x'} Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'
                        Python · read names and marks
                        d = {}
                        n = int(input('How many students? '))
                        for i in range(n):
                            name = input('Name: ')
                            d[name] = int(input('Marks: '))
                        print(d)
                        Output · the user types 2 students
                        How many students? 2 Name: Asha Marks: 91 Name: Ravi Marks: 78 {'Asha': 91, 'Ravi': 78}

                        Accessing items using keys #accessing

                        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.

                        Adding an item #adding

                        Assigning to a new key adds a pair at the end.

                        Python shell
                        >>> d = {'a': 1} >>> d['b'] = 2 >>> d {'a': 1, 'b': 2}

                        Modifying an item #modifying

                        Assigning to an existing key replaces its value; the key keeps its place.

                        Python shell
                        >>> d = {'a': 1, 'b': 2} >>> d['a'] = 100 >>> d {'a': 100, 'b': 2}

                        Deleting an item #deleting

                        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')
                        Output
                        Asha 91 Ravi 78 Meena 85 Asha scored above 80 Meena scored above 80
                        Python · values and keys
                        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

                        dict(a=1, b=2)'a'1'b'2dict([('x', 10), ('y', 20)])'x'10'y'20dict.fromkeys(['a', 'b'], 0)'a'0'b'011-CS · 12-CSlen(dict(a=1, b=2))→ 2 pairs
                        Three ways to build a dictionary; len() counts key: value pairs, not keys and values separately.

                        len(d) #len

                        Number of key: value pairs.

                        >>> len({'a': 1, 'b': 2}) 2 >>> len({}) 0

                        dict() #dict

                        Builds a dictionary from name=value arguments or from pairs.

                        >>> dict(a=1, b=2) {'a': 1, 'b': 2} >>> dict([('x', 10), ('y', 20)]) {'x': 10, 'y': 20}

                        dict.fromkeys(keys[, v]) 11-CS · 12-CS #fromkeys

                        A new dictionary with these keys, each with value v (None by default).

                        >>> dict.fromkeys(['a', 'b']) {'a': None, 'b': None} >>> dict.fromkeys(['a', 'b'], 0) {'a': 0, 'b': 0}

                        Looking inside

                        d = {'a': 1, 'b': 2, 'c': 3}'a'1'b'2'c'3d.keys()dict_keys(['a', 'b', 'c'])the left of every paird.values()dict_values([1, 2, 3])the right of every paird.items()dict_items([('a', 1), ('b', 2), ('c', 3)])each whole pair, as a tuple
                        keys(), values() and items() give views of the dictionary; wrap them in list() to get a plain list. A for loop over items() gives each pair.

                        d.keys() #keys

                        A view of all keys; list() makes it a list.

                        >>> d = {'a': 1, 'b': 2} >>> d.keys() dict_keys(['a', 'b']) >>> list(d.keys()) ['a', 'b']

                        d.values() #values

                        A view of all values.

                        >>> d = {'a': 1, 'b': 2} >>> d.values() dict_values([1, 2]) >>> sum(d.values()) 3

                        d.items() #items

                        A view of (key, value) tuples.

                        >>> d = {'a': 1, 'b': 2} >>> d.items() dict_items([('a', 1), ('b', 2)])

                        Getting and adding

                        d'a'1the dictionary each row starts fromd.get('b', 0)'a'1→ 0; d is not changedd.setdefault('b', 50)'a'1'b'50→ 50; 'b' addedd.update({'a': 10, 'c': 3})'a'10'c'3'a' changed, 'c' added
                        get() only reads; setdefault() adds a key only if it is missing; update() adds new keys and overwrites existing ones.

                        d.get(k[, default]) 11-CS · 12-CS #get

                        The value of k, or None (or default) if absent: no KeyError.

                        >>> d = {'a': 1, 'b': 2} >>> d.get('a') 1 >>> print(d.get('z')) None >>> d.get('z', 0) 0

                        d.setdefault(k, v) 11-CS · 12-CS #setdefault

                        If k exists, returns its value and changes nothing; else adds k: v and returns v.

                        >>> d = {'a': 1} >>> d.setdefault('a', 50) 1 >>> d.setdefault('b', 50) 50 >>> d {'a': 1, 'b': 50}

                        d.update(d2) #update

                        Adds the pairs of d2; existing keys get d2's values.

                        >>> d = {'a': 1, 'b': 2} >>> d.update({'b': 20, 'c': 3}) >>> d {'a': 1, 'b': 20, 'c': 3}

                        Removing

                        d'a'1'b'2'c'3the starting dictionarydel d['a']'a'1'b'2'c'3removes that paird.pop('b')'a'1'b'2'c'3removes 'b'; returns 2d.popitem()'a'1'b'2'c'3last pair; returns ('c', 3)d.clear()'a'1'b'2'c'3all pairs gone; d is {}
                        del and pop() remove by key; popitem() always removes the pair added last; clear() empties the dictionary but keeps it.

                        del d[k] · del d #del

                        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

                        d.pop(k[, default]) 11-CS · 12-CS #pop

                        Removes k and returns its value; default instead of KeyError.

                        >>> d = {'a': 1, 'b': 2} >>> d.pop('a') 1 >>> d {'b': 2} >>> d.pop('z', 'none') 'none' >>> d.pop('z') Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'z'

                        d.popitem() 11-CS · 12-CS #popitem

                        Removes and returns the last added pair, as a tuple.

                        >>> d = {'a': 1, 'b': 2, 'c': 3} >>> d.popitem() ('c', 3) >>> d {'a': 1, 'b': 2} >>> {}.popitem() Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'popitem(): dictionary is empty'

                        d.clear() #clear

                        Removes every pair; d still exists, now empty.

                        >>> d = {'a': 1, 'b': 2} >>> d.clear() >>> d {}

                        Copying

                        e = d (no copy)e = d.copy()de'a'9e['a'] = 9 changes the ONE dictionary:d['a'] is 9 toode'a'1'a'9two dictionaries: e['a'] = 9leaves d['a'] as 1
                        Assigning a dictionary to another name never copies it; copy() does.

                        d.copy() 11-CS · 12-CS #copy

                        A separate copy; changing it leaves d alone (unlike e = d).

                        >>> d = {'a': 1} >>> e = d.copy() >>> e['a'] = 9 >>> d, e ({'a': 1}, {'a': 9})

                        Summarising

                        d = {'Ravi': 78, 'Asha': 91, 'Meena': 85}'Ravi'78'Asha'91'Meena'85max(d)→ 'Ravi'compares keys: 'Ravi' is lastmin(d)→ 'Asha'the alphabetically first keymax(d.values())→ 91the highest valuemax(d, key=d.get)→ 'Asha'the key with the highest valuesorted(d)→ ['Asha', 'Meena', 'Ravi']a sorted list of the keys
                        Used on a dictionary, max(), min() and sorted() look at the keys. Pass d.values() to work on the values.

                        max(d) 11-CS · 12-CS #max

                        The largest key. For the largest value use d.values(); for the key with it, key=d.get.

                        >>> d = {'Asha': 91, 'Ravi': 78, 'Meena': 85} >>> max(d) 'Ravi' >>> max(d.values()) 91 >>> max(d, key=d.get) 'Asha'

                        min(d) 11-CS · 12-CS #min

                        The smallest key; min(d.values()) for the smallest value.

                        >>> d = {'Asha': 91, 'Ravi': 78, 'Meena': 85} >>> min(d) 'Asha' >>> min(d.values()) 78

                        sorted(d) 11-CS · 12-CS #sorted

                        A sorted list of the keys; of items, sorted by key.

                        >>> d = {'Ravi': 78, 'Asha': 91, 'Meena': 85} >>> sorted(d) ['Asha', 'Meena', 'Ravi'] >>> sorted(d.values()) [78, 85, 91] >>> sorted(d.items()) [('Asha', 91), ('Meena', 85), ('Ravi', 78)]
                        Often confusedDifference
                        d[k] vs d.get(k)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 dclear 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.

                        Character count #character-count

                        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)
                        Output
                        {'m': 1, 'i': 4, 's': 4, 'p': 2} True

                        Employee salary #employee-salary

                        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'))
                        Output · the user types 3 employees, then Iyer
                        Employees: 3 Name: Rao Salary: 45000 Name: Iyer Salary: 52000 Name: Khan Salary: 39000 Rao 45000 Iyer 52000 Khan 39000 Whose salary? Iyer Iyer earns 52000
                        Exam tip

                        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)
                        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))
                        d = {'x': '123', 'y': '456'}
                        res = ''
                        for k in d:
                            res += d[k].isdigit() * 5
                        print(res)
                        d = {'a': 1, 'b': 2}
                        print(d.get('c', 'Missing'), d.get('a', 'No'))
                        d = {'apple': 15, 'banana': 7, 'cherry': 9}
                        s = ''
                        for key in d:
                            s = s + str(d[key]) + '@'
                        print(s[:-1])

                        Self-check quiz

                        Which can NOT be a dictionary key?
                        For d = {'a': 1}, d['b'] gives:
                        d = {'x': 5}; d['x'] = 7; d['y'] = 9. Now d is:
                        A for loop over a dictionary gives its:
                        Which removes every item but keeps the dictionary?
                        dict.fromkeys(['a', 'b'], 0) is:
                        For d = {'Asha': 91, 'Ravi': 78}, max(d) is:
                        d = {'a': 1}; d.setdefault('a', 5) returns:
                        len({1: 'a', 2: 'b', 1: 'c'}) is:
                        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.

                          import mathone name: the module from mathimport sqrtthe function itself mathsqrtsqrt() math.sqrt(16)sqrt(16) MODULE math pi eceil() floor()pow() fabs() sin() cos() tan()
                          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 module #import

                          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 … import #from-import

                          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.pi #pi

                          The constant π, to 15 decimal places. A value, not a function: no brackets.

                          >>> import math >>> math.pi 3.141592653589793 >>> round(math.pi, 2) 3.14

                          math.e #e

                          The constant e, the base of natural logarithms.

                          >>> import math >>> math.e 2.718281828459045

                          math.sqrt(x) #sqrt

                          Square root, always a float. A negative x is a ValueError.

                          >>> import math >>> math.sqrt(25) 5.0 >>> math.sqrt(2) 1.4142135623730951 >>> math.sqrt(-4) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: math domain error

                          math.ceil(x) #ceil

                          The smallest integer ≥ x: rounds up, towards +∞.

                          >>> import math >>> math.ceil(4.2) 5 >>> math.ceil(-4.2) -4 >>> math.ceil(5) 5

                          math.floor(x) #floor

                          The largest integer ≤ x: rounds down, towards −∞.

                          >>> import math >>> math.floor(4.8) 4 >>> math.floor(-4.2) -5

                          math.pow(x, y) #pow

                          x to the power y, always a float; ** keeps ints as ints.

                          >>> import math >>> math.pow(2, 3) 8.0 >>> 2 ** 3 8

                          math.fabs(x) #fabs

                          Absolute value as a float; built-in abs() keeps the type.

                          >>> import math >>> math.fabs(-7) 7.0 >>> abs(-7) 7

                          math.sin(x) #sin

                          Sine of x radians. sin(30) is 30 radians, not 30°.

                          >>> import math >>> math.sin(math.pi / 2) 1.0 >>> math.sin(0) 0.0 >>> math.sin(30) -0.9880316240928618

                          math.cos(x) #cos

                          Cosine of x radians.

                          >>> import math >>> math.cos(0) 1.0 >>> math.cos(math.pi) -1.0

                          math.tan(x) #tan

                          Tangent of x radians. Floats are approximate: tan(π/4) is not exactly 1.

                          >>> import math >>> math.tan(0) 0.0 >>> math.tan(math.pi / 4) 0.9999999999999999
                          Exam tip

                          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() #random

                          random.random() gives a float from 0.0 up to, but not including, 1.0. Multiply to stretch the range: random.random() * 10 is from 0.0 to under 10.0.

                          Python shell · one possible run
                          >>> import random >>> random.random() 0.32383276483316237 >>> random.random() 0.15084917392450192 >>> random.random() * 10 6.509344730398538

                          randint(a, b) #randint

                          random.randint(a, b) gives a whole number from a to b, both included. randint(1, 6) is a dice roll: 1, 2, 3, 4, 5 or 6.

                          Python shell · one possible run
                          >>> import random >>> random.randint(1, 6) 4 >>> random.randint(1, 6) 5 >>> random.randint(1, 6) 4 >>> random.randint(-2, 2) 1

                          randrange(start, stop, step) #randrange

                          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)
                          CallPossible valuesCount
                          random()0.0 ≤ x < 1.0 (a float)—
                          randint(1, 5)1, 2, 3, 4, 55
                          randrange(1, 5)1, 2, 3, 44
                          randrange(5)0, 1, 2, 3, 45
                          randrange(0, 10, 3)0, 3, 6, 94

                          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)
                          Output · start, end, what is printed
                          1 2 15#25# 1 3 15#25#35# 1 4 15#25#35#45# 2 2 25# 2 3 25#35# 2 4 25#35#45#
                          OptionPossible?Why
                          (a) 5#15#✗ Nostart is at least 1, so nums[0] = 5 is never printed
                          (b) 15#35#✗ NoThe loop prints consecutive items; it can't skip 25
                          (c) 15#25#35#45#✓ Yesstart = 1, end = 4
                          (d) 35#45#✗ NoThe 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.

                          mean(data) #mean

                          The arithmetic mean: sum ÷ count. For whole numbers that divide exactly, it gives an int.

                          >>> import statistics >>> statistics.mean([10, 20, 30, 45]) 26.25 >>> statistics.mean([2, 4]) 3

                          median(data) #median

                          The middle value after sorting. With an even count, the mean of the two middle values.

                          >>> import statistics >>> statistics.median([7, 1, 5]) 5 >>> statistics.median([7, 1, 5, 3]) 4.0

                          mode(data) #mode

                          The most frequent value; works for strings too. On a tie, the one that comes first.

                          >>> import statistics as s >>> s.mode([10, 20, 10, 30, 10, 20, 30]) 10 >>> s.mode(['a', 'b', 'b']) 'b' >>> s.mode([1, 2, 3]) 1
                          Exam tip

                          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))
                          import math
                          print(math.pow(2, 3), 2 ** 3, math.sqrt(16))
                          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

                          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?

                          Self-check quiz

                          After from math import sqrt, which call works?
                          math.floor(-7.2) is:
                          Which can give 10?
                          math.pow(3, 2) returns:
                          With a = random.randint(3, 5) and b = random.randint(2, 3), the minimum and maximum of a + b are:
                          statistics.median([4, 1, 3, 2]) is:
                          Which module has mode()?
                          "randrange(1, 5) gives 1 to 4 only, while randint(1, 5) gives 1 to 5." This is:
                          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.

                            Built-in functions #built-in

                            Built-in functions are always available, with no import: print(), input(), len(), int(), type(), abs(), max(), range() …

                            Functions in modules #module

                            Module functions are defined inside a module and need an import first (MOD.01): math.sqrt(), random.randint(), statistics.mean(), pickle.dump().

                            User-defined functions #user-defined

                            User-defined functions are written by the programmer with def, for the program's own tasks. The rest of this chapter is about them.

                            Python shell · one of each
                            >>> len('KV'), abs(-5), max(3, 9) (2, 5, 9) >>> import math >>> math.sqrt(81) 9.0 >>> def double(x): ... return x * 2 ... >>> double(21) 42
                            Exam tip

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

                            def interest(p, r, t): """Simple interest.""" si = p * r * t / 100 return si amount = interest(5000, 8, 2) HEADER · def, name, parameters, : DOCSTRING · optional note BODY · indented under the header RETURN · sends a value back CALL · arguments fill parameters
                            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.

                            pr = 8t = 15000t=3 PARAMETERSARGUMENTS def interest(p, r=8, t=1): by positionby name no argument:uses default 8 interest(5000, t=3) → p = 5000, r = 8, t = 3
                            Positional arguments fill parameters in order; keyword arguments name the parameter; a parameter with a default needs no argument at all.

                            Positional parameters #positional

                            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
                            Output
                            32 25

                            Default parameters #default

                            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 parameters #named

                            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'

                            Passing mutable and immutable arguments #passing-arguments

                            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.

                            IMMUTABLE · x = x + 5nxcallerparameter1015x moves to a new int; n still 10MUTABLE, CHANGED · L.append(4)mLcallerparameter[1, 2, 3, 4]one list, two names: m sees the 4MUTABLE, REASSIGNED · L = [0]mLcallerparameter[1, 2, 3][0]L moves to a new list; m unchangedA COPY PASSED · f(m[:])mLcallerparameter[1, 2, 3][1, 2, 3, 4]only the copy got the 4
                            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.
                            ArgumentInside the functionDoes the caller see it?
                            Immutable: int, float, str, tupleAny change, e.g. x = x + 5, s += '!'✗ No: a new object is made; only the parameter moves to it
                            Mutable: list, dictionaryChanged in place: L.append(4), L[0] = 9, L += [9], d[k] = v✓ Yes: there is only one object
                            Mutable: list, dictionaryGiven 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)
                            Output
                            [1, 9] [1]
                            Python · a dictionary is mutable too
                            def give_bonus(d, name):
                                d[name] = d[name] + 5
                            
                            marks = {'Asha': 85, 'Ravi': 70}
                            give_bonus(marks, 'Ravi')
                            print(marks)
                            Output
                            {'Asha': 85, 'Ravi': 75}

                            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.
                            Python · two values back
                            def min_max(L):
                                return min(L), max(L)
                            
                            lo, hi = min_max([7, 2, 9, 4])
                            print(lo, hi)
                            print(min_max([5, 1]))
                            Output
                            2 9 (1, 5)
                            Python · return leaves early
                            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.

                            def area(l, b): … print('1. before the call') x = area(4, 5) print('3. back again …') def area(l, b): print('2. inside area') return l * b MAIN PROGRAMFUNCTION area() call20 order: def remembered → print 1 → call → print 2 → return 20 → back at the call, x = 20 → print 3
                            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).

                            BUILT-IN · print len input range GLOBAL · total = 100 x = 10 show() LOCAL · inside show(): count = 5 exists only while show() runs can read total and x to change x: global x lookup goes outwards:local → global → built-in
                            A function can see outwards (it can read globals) but the program cannot see in: count does not exist outside show().

                            Global scope #global

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

                            Local scope #local

                            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.

                            Python · a local can't be seen outside
                            def f():
                                count = 5            # local variable
                                print('inside:', count)
                            
                            f()
                            print(count)
                            Output
                            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.

                            BUILT-IN · print len input GLOBAL · x = 'global' outer() ENCLOSING · outer(): y = 'enclosing' LOCAL · inner(): z = 'local' print(z, y, x, len('abc')) → local enclosing global 3 inner() is defined inside outer(),so only outer() can call it the main program can call outer() but not inner() LOOKUP FROM inner() z → L ✓ y → L, E ✓ x → L, E, G ✓ len → L, E, G, B ✓ w → not found: NameError L local · E enclosing G global · B built-in
                            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)
                            def swap(A, B):
                                A, B = B, A
                                print(A, '#', B)
                                return A
                            
                            C = 120
                            D = 240
                            C = swap(C, D)
                            print(C, '#', D)
                            def f(a, b=2, c=3):
                                return a + b * c
                            
                            print(f(1), f(1, c=1), f(c=2, a=3))
                            c = 10
                            
                            def add():
                                global c
                                c = c + 2
                            
                            print(c, end='#')
                            add()
                            c = 15
                            print(c, end='%')
                            def change(a, b):
                                a = a * 2
                                b[0] = b[0] * 2
                            
                            x = 5
                            y = [5]
                            change(x, y)
                            print(x, y)
                            a = 1
                            
                            def f():
                                a = 2
                                def g():
                                    print(a, end=' ')
                                g()
                                print(a, end=' ')
                            
                            f()
                            print(a)
                            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='#')

                            Self-check quiz

                            Which function header is correct?
                            A function with no return statement returns:
                            return a, b sends back:
                            In def area(l, b): and the call area(4, 5), the values 4 and 5 are:
                            Which call is a SyntaxError for def f(a, b):?
                            In def change(): n = 10; x = 5, n and x are:
                            Which statement lets a function assign to a global variable x?
                            In the LEGB rule, which scope is searched first?
                            A list passed to a function is changed inside it with L.append(9). After the call:
                            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 exceptionRaised when
                              ZeroDivisionErrorDividing by zero
                              ValueErrorThe value is wrong for the operation: int('abc')
                              TypeErrorThe type is wrong: '5' + 5
                              NameErrorA name that is not defined
                              IndexError · KeyErrorA list index out of range · a missing dictionary key
                              FileNotFoundErrorOpening a missing file for reading
                              EOFErrorReading past the end of a file, e.g. pickle.load() (BIN.02)
                              ImportErrorAn 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.

                              TRY blockerror?matches? ELSE blockEXCEPT blockFINALLY NoYesYesNo After finally, the program goes on with the next statement. If no except matched, the error carries on after finally and stops the program with a traceback.
                              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.

                              try #try

                              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.

                              except #except

                              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.

                              finally #finally

                              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
                              Python · try with finally only
                              try:
                                  print('working ...')
                              finally:
                                  print('cleaning up')
                              Output
                              working ... cleaning up
                              Python · no matching except
                              try:
                                  total = 'Total: ' + 50
                              except ZeroDivisionError:
                                  print('divide error')
                              finally:
                                  print('finally runs first')
                              print('never reached')
                              Output
                              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.

                              Chapter practice · EXC

                              Check your understanding

                              Predict the output

                              try:
                                  print('A')
                                  x = 5 / 1
                                  print('B')
                              except ZeroDivisionError:
                                  print('C')
                              else:
                                  print('D')
                              finally:
                                  print('E')
                              try:
                                  print('A')
                                  x = 5 / 0
                                  print('B')
                              except ZeroDivisionError:
                                  print('C')
                              else:
                                  print('D')
                              finally:
                                  print('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!')
                              try:
                                  x = int('abc')
                              except ValueError:
                                  print('Value error!')
                              except Exception:
                                  print('General error!')

                              Self-check quiz

                              When is the else part of try-except-else executed?
                              Which is true about try-except-finally?
                              Which error can NOT be handled with try-except?
                              Where should except Exception: go among several except blocks?
                              If an error in try is not matched by any except:
                              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.

                                TEXT FILE · .txtBINARY FILE · .datCSV FILE · .csv Asha 91↵Ravi 78↵ 80 04 95 0e 005d 94 28 8c … Name,Marks↵Asha,91↵Ravi,78↵ characters in lines;↵ is the EOL characteropens in Notepad bytes, as kept in memory;not readable as textread with pickle a text file of rows;values split by commasopens in Excel too
                                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.

                                Text file #text

                                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.

                                Binary file #binary

                                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.

                                CSV file #csv

                                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())
                                Output · what each file holds
                                Asha 91 Asha,91 b'\x80\x04\x95\x0e\x00\x00\x00\x00\x00\x00\x00]\x94(\x8c\x04Asha\x94K[e.'
                                Text fileBinary fileCSV file
                                StoresCharacters, in linesBytes, as in memoryCharacters: rows of comma-separated values
                                Readable by people?YesNoYes
                                EOL charactersYes, '\n'NoYes, one per row
                                Python reads withread(), readline()pickle.load()csv.reader()
                                Open modes'r' 'w' 'a' …'rb' 'wb' 'ab' …'r' 'w' 'a' with newline=''
                                Good forNotes, logs, programsSaving Python objects quicklyTables shared with spreadsheets
                                Exam tip

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

                                C:\SchoolDataNotesmarks.txtreport.txt ABSOLUTE · from the rootC:\School\Data\marks.txt RELATIVE · from SchoolData\marks.txt RELATIVE · from Data..\Notes\report.txt ← current 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.

                                Python · four ways to write one path
                                print('C:\new\data.txt')
                                print('C:\\new\\data.txt')
                                print(r'C:\new\data.txt')
                                print('C:/new/data.txt')
                                Output · the first is broken by \n
                                C: ew\data.txt C:\new\data.txt C:\new\data.txt C:/new/data.txt
                                Exam tip

                                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?
                                The EOL character in Python is:
                                A CSV file is:
                                Which is an absolute path?
                                In a path, .. means:
                                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.

                                  def count_lines():every step below goes in the function bodyWRITE · create or add1 · OPEN · 'w' new, 'a' addwith open('story.txt', 'w') as f:2 · GET THE DATAline = input('Line: ')3 · WRITE · strings only, add '\n'f.write(line + '\n')4 · CLOSE · automatic at the end of with(or f.close() without with)READ · count, search, show1 · OPEN · 'r'with open('story.txt') as f:2 · READ · pick the one the task needstext = f.read()charactersfor line in f:lineswords = f.read().split()words3 · TEST AND COUNTif line[0] in 'TA':c += 14 · SHOWprint('Lines:', c)count_lines() ← and call it, if the question says "write and call"
                                  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 clause #with

                                  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.

                                  Hello␣world↵ r · r+ start here (0)a · a+ start at the end w · w+ empty the file first; pointer at 0 (empty: old data is gone) old fileafter w
                                  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.
                                  ModeMeaningFile missing?Old dataPointer starts
                                  'r'Read only (the default)FileNotFoundErrorKeptBeginning
                                  'r+'Read and writeFileNotFoundErrorKept; writing overwritesBeginning
                                  'w'Write onlyCreatedErasedBeginning
                                  'w+'Write and readCreatedErasedBeginning
                                  'a'Append: write at the endCreatedKeptEnd
                                  'a+'Append and readCreatedKeptEnd (writes always go there)

                                  r #r

                                  '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+ #r-plus

                                  '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())
                                  Output
                                  ABC xyCDEFGH

                                  w #w

                                  '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='')
                                  Output
                                  second version

                                  w+ #w-plus

                                  'w+' is w plus reading. After writing, the pointer is at the end, so seek(0) before reading back.

                                  Python · write, rewind, read
                                  with open('temp.txt', 'w+') as f:
                                      f.write('hello')
                                      print(repr(f.read()))   # pointer at the end
                                      f.seek(0)
                                      print(f.read())
                                  Output
                                  '' hello

                                  a #a

                                  '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='')
                                  Output
                                  line 1 line 2

                                  a+ #a-plus

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

                                  write() #write

                                  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

                                  writelines() #writelines

                                  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.

                                  story.txt line 1↵line 2↵line 3↵ read() → 'line 1\nline 2\nline 3\n'readline() → 'line 1\n' (next call: line 2)readlines() → ['line 1\n', 'line 2\n', …] read(n): the next n characters only.At the end of the file read() and readline() return '' (an empty string).
                                  read() and readline() give a string; readlines() gives a list of strings. All of them keep the '\n' at the end of each line.

                                  read() #read

                                  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')
                                  Output
                                  My first book was 126 characters were left

                                  readline() #readline

                                  f.readline() reads one line, up to and including its '\n'. Each call gives the next line; at the end it gives ''.

                                  Python · one line at a time
                                  f = open('story.txt')
                                  print(f.readline(), end='')
                                  print(f.readline(), end='')
                                  print(repr(f.readline()))
                                  f.close()
                                  Output · the third line shown with repr()
                                  My first book was Me and My Family. It gave me a chance to be known to the world. 'The world has 195 countries.\n'

                                  readlines() #readlines

                                  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.

                                  My␣first␣book␣ 012345678910111213 after read(10): tell() → 10seek(3) puts it here filled: the 10 characters read(10) took; the next read starts at 'o'
                                  The pointer always sits between characters. Position 10 means 10 characters are behind it, and the next read starts with the character numbered 10.

                                  tell() #tell

                                  f.tell() returns the pointer's current position as an integer: the number of bytes from the start of the file.

                                  seek() #seek

                                  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.

                                  TaskPattern
                                  Count characters (vowels, digits, capitals)text = f.read(), then for ch in text:
                                  Count words, or a particular wordwords = f.read().split(), then for w in words:
                                  Show or count certain linesfor line in f:, test line[0], line.startswith() or in line
                                  Change the fileRead 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()
                                  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())
                                  with open('story.txt') as f:
                                      L = f.readlines()
                                  print(len(L), L[1].split()[1])

                                  Self-check quiz

                                  Which mode opens a text file to add data at the end, keeping what is there?
                                  f.readlines() returns:
                                  What does f.read(5) return?
                                  Opening a file that does not exist in 'w' mode:
                                  Which statement gives the file pointer's current position?
                                  f.writelines(['a', 'b']) writes:
                                  The main advantage of with open(…) as f: is:
                                  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.

                                    def show_records():every step below goes in the function bodyWRITE · create or add1 · IMPORTimport pickle2 · OPEN · 'wb' new, 'ab' addwith open('stu.dat', 'ab') as f:3 · BUILD ONE RECORDrec = [roll, name, marks]4 · DUMP · once per recordpickle.dump(rec, f)READ · show, search, count1 · IMPORTimport pickle2 · OPEN · 'rb'with open('stu.dat', 'rb') as f:3 · LOAD IN A LOOPtry:while True:rec = pickle.load(f)4 · TEST AND SHOWif rec[2] > 75:print(rec)5 · STOP AT THE ENDexcept EOFError:passUPDATE OR DELETE · three stages1 READ ALLrecords.append(rec)2 CHANGE / DROPrec[2] = new3 WRITE ALL · 'wb'pickle.dump(rec, f)show_records() ← and call it, if the question says "write and call"
                                    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.

                                    ModeMeaningFile missing?Old dataTypical use
                                    'rb'Read onlyFileNotFoundErrorKeptShow or search records
                                    'rb+'Read and writeFileNotFoundErrorKeptUpdate a record in place
                                    'wb'Write onlyCreatedErasedCreate a new file; rewrite after changes
                                    'wb+'Write and readCreatedErasedCreate, then read back
                                    'ab'AppendCreatedKept; writes at the endAdd new records
                                    'ab+'Append and readCreatedKept; writes at the endAdd, then read all

                                    rb #rb

                                    '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'

                                    rb+ #rb-plus

                                    'rb+' reads and writes an existing file without erasing it: used to overwrite one record where it stands (the last example in BIN.03).

                                    wb #wb

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

                                    wb+ #wb-plus

                                    'wb+' is wb with reading too: write, seek(0), then read back what was written.

                                    ab #ab

                                    '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+ #ab-plus

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

                                    [1, 'Asha', 91]pickle.dump(obj, f)bytes in stu.dat [1, 'Asha', 91]obj = pickle.load(f)bytes in stu.dat PICKLING · an object becomes bytesUNPICKLING · the bytes become the same object The file must be opened in a binary mode: 'wb' or 'ab' to dump, 'rb' to load.
                                    dump writes one object each time it is called; load reads one object each time, in the same order.

                                    dump() #dump

                                    pickle.dump(object, fileobject) writes one object to a file opened with 'wb' or 'ab'. Call it once per record. It returns None.

                                    load() #load

                                    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))
                                    Output
                                    {'roll': 1, 'name': 'Asha', 'marks': 91} True <class 'dict'>
                                    Python · one load too many
                                    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.

                                    Read #read

                                    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()
                                    Output
                                    [1, 'Asha', 91.0] [2, 'Ravi', 72.0] [3, 'Meena', 85.0] [4, 'Kabir', 64.0]

                                    Write / create #write-create

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

                                    Append #append

                                    Open with 'ab' so the old records stay, and dump the new one; it goes at the end.

                                    Python · add one record
                                    import pickle
                                    def add_record(rec):
                                        with open('stu.dat', 'ab') as f:  # keeps old
                                            pickle.dump(rec, f)
                                    
                                    add_record([5, 'Isha', 78.0])
                                    show_all()
                                    Output · show_all() after
                                    [1, 'Asha', 91.0] [2, 'Ravi', 72.0] [3, 'Meena', 85.0] [4, 'Kabir', 64.0] [5, 'Isha', 78.0]

                                    Update #update

                                    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()
                                    Output · Ravi's marks are now 95.0
                                    [1, 'Asha', 91.0] [2, 'Ravi', 95.0] [3, 'Meena', 85.0] [4, 'Kabir', 64.0]
                                    Python · delete records
                                    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()
                                    Output · Kabir (64) is gone
                                    [1, 'Asha', 91.0] [2, 'Ravi', 72.0] [3, 'Meena', 85.0]

                                    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()
                                    Output
                                    [1, 'Asha', 91.0] [2, 'Ravi', 72.0] [3, 'Meena', 85.0] [4, 'Kabir', 70.0]
                                    Exam tip

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

                                    A program opens stu.dat with 'wb' to add one new record. What happens to the four records already there?

                                    Self-check quiz

                                    Which mode opens a binary file for reading and writing without erasing it?
                                    Which is the correct way to load an object from a binary file?
                                    Opening a missing file in 'rb' mode:
                                    pickle.load() raises which exception at the end of the file?
                                    The order of arguments in pickle.dump() is:
                                    To add a new record to an existing binary file, open it with:
                                    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.

                                      def search():every step below goes in the function bodyWRITE · create or add1 · IMPORTimport csv2 · OPEN · 'w' new, 'a' addwith open('m.csv', 'a', newline='') as f:3 · MAKE A WRITERw = csv.writer(f)4 · WRITE · one list per recordw.writerow([roll, name, marks])READ · show, search, count1 · IMPORTimport csv2 · OPEN · 'r'with open('m.csv', newline='') as f:3 · LOOP OVER THE READERfor row in csv.reader(f):4 · TEST · values are stringsif int(row[2]) > 75:5 · SHOWprint(row)search() ← and call it, if the question says "write and call"
                                      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'.

                                      ['Asha', 91]writer(f).writerow(row)Asha,91↵ ['Asha', '91']for row in reader(f)Asha,91↵ WRITING · a list becomes one lineREADING · each line becomes a listmarks.csv Every value comes back as a string: 91 is written, '91' is read. Convert with int() or float().
                                      The filled box is the trap: the reader cannot know that 91 was a number, because the file holds only characters.

                                      Opening and closing a CSV file #open-close

                                      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.

                                      ToWrite
                                      Create or overwritef = open('marks.csv', 'w', newline='')
                                      Add rows at the endf = open('marks.csv', 'a', newline='')
                                      Readf = open('marks.csv', 'r', newline='')
                                      Closef.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.

                                      writer() #writer

                                      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='')
                                      Output · city.csv
                                      Kochi;Kerala New Delhi, India;Delhi

                                      writerow() #writerow

                                      w.writerow(row) writes one row: one list becomes one line. Write a heading row first, so the columns are named.

                                      writerows() #writerows

                                      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.

                                      reader() #reader

                                      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)
                                      Output · note the quotes: all strings
                                      ['Roll', 'Name', 'Marks'] ['1', 'Asha', '91'] ['2', 'Ravi', '72'] ['3', 'Meena', '85']
                                      Python · skip the heading, filter on a number
                                      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:

                                      Product.csv
                                      pid,pname,price P1,Oven,25000 P2,Iron,1800 P3,Laptop,62000 P4,AC,41000
                                      Output
                                      P1 Oven 25000 P4 AC 41000
                                      Python · search with two conditions
                                      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])

                                      Self-check quiz

                                      Each row given by csv.reader is:
                                      Which writes several rows in one call?
                                      Why is newline='' passed to open() for a CSV file?
                                      The default delimiter of the csv writer is:
                                      To add a record to an existing CSV file without losing data, open it with:
                                      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.

                                        10 1020 102030 1020 (empty) toptoptoptop 30 comes off s = []push(10)push(20)push(30)pop() → 30 LIFO: the last item pushed is the first popped
                                        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.

                                        push #push

                                        Push adds an item on top of the stack. With a list whose end is the top, push is stack.append(item).

                                        pop #pop

                                        Pop removes and returns the top item: stack.pop(), with no index. Check for an empty stack first; popping an empty one is underflow.

                                        Python shell · a list used as a stack
                                        >>> stack = [] >>> stack.append(10) >>> stack.append(20) >>> stack.append(30) >>> stack [10, 20, 30] >>> stack[-1] 30 >>> stack.pop() 30 >>> stack [10, 20] >>> len(stack) == 0 False
                                        OperationWith a listEmpty stack?
                                        push(x)stack.append(x)Fine
                                        pop()stack.pop()Underflow: check stack == [] first
                                        peek()stack[-1]IndexError: check first
                                        is emptystack == [] or len(stack) == 0True
                                        displayfor x in stack[::-1]: (top first)Prints nothing
                                        Common mistake

                                        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()
                                        Output · popped in reverse order
                                        [10025, 254923, 1297653, 31498, 92765] 92765 31498 1297653 254923 10025 Stack Empty
                                        Python · records: products costing more than 50
                                        L = [('Laptop', 90000), ('Mobile', 30000),
                                             ('Pen', 50), ('Headphones', 1500)]
                                        Product = []
                                        
                                        def Push_element():
                                            for item in L:
                                                if item[1] > 50:
                                                    Product.append(item)
                                        
                                        def Pop_element():
                                            while len(Product) > 0:
                                                print(Product.pop())
                                            print('Stack Empty')
                                        
                                        Push_element()
                                        print(Product)
                                        Pop_element()
                                        Output
                                        [('Laptop', 90000), ('Mobile', 30000), ('Headphones', 1500)] ('Headphones', 1500) ('Mobile', 30000) ('Laptop', 90000) Stack Empty
                                        Python · from a dictionary: events above 200
                                        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)
                                        st = []
                                        for w in 'to be or not'.split():
                                            st.append(w)
                                        print(st.pop(), st.pop(), st)

                                        Self-check quiz

                                        A stack works on the principle:
                                        Which pointer is associated with a stack?
                                        Popping from an empty stack is called:
                                        With a list S as a stack (end = top), push is:
                                        After push 4, push 7, pop, push 2, what is on top?
                                        Which is NOT a use of a stack?
                                        Your score
                                        – / 6
                                        Answer every question to see your score.

                                        One-page revision

                                        Stackadd and remove at one end: the top
                                        LIFOlast in, first out
                                        push(x)stack.append(x)
                                        pop()stack.pop(): removes and returns the top
                                        peekstack[-1]: look, don't remove
                                        Empty?stack == [] (check before pop)
                                        Underflowpop from an empty stack
                                        Overflowpush onto a full stack
                                        Displayfor x in stack[::-1]: top first
                                        Usesundo, back button, reversing, brackets