Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🐍 Unit 1 – Programming 2 (40 marks)  ·  Lesson 10

📝 Unit 1 Board Questions + Practice

What is on this page

Unit 1 of the 2026-27 syllabus carries 40 marks. Part A has 36 new practice questions with answers (click "Show answer" only after you try). Part B has all 47 questions of Unit 1 from the previous CBSE board papers (2022, 2023, 2026) in their original form – tables, code and internal choices included – each with a worked answer.

How to use for best result

1) Read the unit lessons first. 2) Solve Part A in your notebook, then check answers. 3) Attempt Part B paper-wise with a timer – about 1.5 minutes per mark. 4) Mark the questions you got wrong and revise that lesson again.

Part A – Practice questions with answers

U1-011 markImportant

State the types of 42 and 42.0. Are the types identical?

Show answer

int and float; the types differ.

U1-021 markImportant

Evaluate: 7 + 12 // 5 * 2 - 9 % 4

Show answer

10.

U1-031 markImportant

Predict both outputs.

Python
print('sCHOOL cODE'.capitalize())
print('book:file:read'.partition(':'))
Show answer

School code; ('book', ':', 'file:read').

U1-041 markImportant

Predict the output.

Python
print('COMPUTER'[-1:1:-2])
Show answer

RTP.

U1-051 markImportant

Which operation is invalid for t=(4,8,12)? (A) t[1] (B) t[1:] (C) t.append(16) (D) len(t)

Show answer

C; tuples have no append method.

U1-061 markImportant

Predict the result.

Python
d = {'A':10, 'B':20, 'A':30}
print(len(d), d['A'])
Show answer

2 30.

U1-071 markImportant

For L=[2,4,6], which raises IndexError: L.pop(2), L.pop(3), L.insert(3,8), or L.append(8)? Treat each independently.

Show answer

L.pop(3).

U1-081 markImportant

Name the file mode that appends binary records without truncating existing contents.

Show answer

ab.

U1-092 marksImportant

Predict the exact output, including the printed return value.

Python
def add(a, b=4):
    print(a+b, end='#')
x = add(3)
print(x)
Show answer

7#None.

U1-102 marksImportant

Predict the two lines of output.

Python
x = 10
def f():
    x = 3
    print(x)
f()
print(x)
Show answer

3 then 10. Assignment inside f creates a local x.

U1-112 marksImportant

Predict the final output and explain why the list and integer behave differently.

Python
def change(items, n):
    items.append(9)
    n += 1
L = [1,2]
a = 5
change(L,a)
print(L,a)
Show answer

[1, 2, 9] 5. The list object is mutated; n is locally rebound.

U1-122 marksImportant

Define total(price, qty=2) to return price*qty. Show calls using the default quantity and a positional quantity of 5.

Show answer

Function and calls:

Python
def total(price, qty=2):
    return price * qty
print(total(100))
print(total(100,5))
U1-132 marksImportant

For d={"R1":80}, use a dictionary method to add R2:75 only if absent, then retrieve R3 with fallback value 0.

Show answer
Python
d.setdefault('R2',75)
d.get('R3',0)
U1-142 marksImportant

Write statements to create a sorted copy of L=[8,3,6] without modifying L, then add the individual elements 10 and 12 to L.

Show answer
Python
new=sorted(L)
L.extend([10,12])
U1-152 marksImportant

Give all possible values of x and the number of loop iterations. Can the code print 40?

Python
import random
L = [10,20,30,40]
for i in range(3):
    x = random.randrange(1,3)
    print(L[x], end=' ')
Show answer

x is 1 or 2; three iterations; outputs are 20 or 30, never 40.

U1-162 marksImportant

Correct the function so that it returns the number of uppercase characters.

Python
def count_upper(s)
    n = 0
    for ch in range(s):
        if ch.isupper:
            n =+ 1
    return ch
Show answer

Corrected function:

Python
def count_upper(s):
    n = 0
    for ch in s:
        if ch.isupper():
            n += 1
    return n
U1-172 marks

Predict the output and name the handled exception.

Python
try:
    print(12//0)
except ZeroDivisionError:
    print('Invalid division')
finally:
    print('Finished')
Show answer

Invalid division, then Finished. ZeroDivisionError is handled.

U1-182 marks

Show one built-in function, one function imported from a module and one user-defined function. Give a valid import and call for the module function.

Show answer

Examples: len([1,2]); from math import sqrt followed by sqrt(81); a user-defined total(price,qty) function.

U1-193 marksImportant

Define adjust(L) to increase each even integer by 2 and decrease each odd integer by 2, modifying L in place. State the result for [4,7,10,13].

Show answer

Result [6,5,12,11].

Python
def adjust(L):
    for i in range(len(L)):
        if L[i] % 2 == 0:
            L[i] += 2
        else:
            L[i] -= 2
U1-203 marks

Define frequency(text) to return a dictionary counting each character, ignoring spaces and letter case. State the result for "A aB".

Show answer

{'a':2,'b':1}

Python
def frequency(text):
    counts = {}
    for ch in text.lower():
        if ch != ' ':
            counts[ch] = counts.get(ch,0) + 1
    return counts
U1-213 marksImportant

Define count_digits(filename) to count and return digit characters in a text file. For text "Lab 12 has 8 PCs", the result must be 3.

Show answer

One valid solution:

Python
def count_digits(filename):
    count = 0
    with open(filename,'r',encoding='utf-8') as f:
        for ch in f.read():
            if ch.isdigit():
                count += 1
    return count
U1-223 marksImportant

Define show_lines(filename) to display only lines with at least 6 whitespace-separated words, without inserting extra blank lines.

Show answer

One valid solution:

Python
def show_lines(filename):
    with open(filename,'r',encoding='utf-8') as f:
        for line in f:
            if len(line.split()) >= 6:
                print(line,end='')
U1-233 marksImportant

Define copy_clean(source,target) to copy only lines that do not contain the letter a in either case. The source and target are different files.

Show answer

One valid solution:

Python
def copy_clean(source,target):
    with open(source,'r',encoding='utf-8') as src:
        with open(target,'w',encoding='utf-8') as dst:
            for line in src:
                if 'a' not in line.lower():
                    dst.write(line)
U1-243 marks

Assume data.bin contains exactly the ASCII bytes ABCDEFG. Predict all four outputs.

Python
with open('data.bin','rb') as f:
    print(f.read(2))
    print(f.tell())
    f.seek(1)
    print(f.read(3))
    print(f.tell())
Show answer

b'AB'; 2; b'BCD'; 4.

U1-253 marks

Differentiate r, w and a for text files. Explain relative versus absolute paths with examples.

Show answer

r reads and requires an existing file; w writes and truncates/creates; a appends/creates. Relative path: data/marks.txt from the current working directory. Absolute path: /school/data/marks.txt on a Unix-like system.

U1-263 marksImportant

Define push_merit(records,stack). Each record is [Name,Marks]. Push the names having Marks >= 85, preserving input order. For [["Asha",90],["Bilal",78],["Charu",88]], an initially empty stack becomes ["Asha","Charu"].

Show answer

One valid solution:

Python
def push_merit(records,stack):
    for name,marks in records:
        if marks >= 85:
            stack.append(name)
U1-273 marksImportant

Define pop_one(stack) to return the top item, or print UNDERFLOW and return None if empty. Define display(stack) to print items top-first without changing the stack.

Show answer

One valid solution:

Python
def pop_one(stack):
    if not stack:
        print('UNDERFLOW')
        return None
    return stack.pop()

def display(stack):
    for item in stack[::-1]:
        print(item)
U1-284 marksImportant

Create books.csv with header BookID,Title,Price and records [101,"Python",450], [102,"SQL",380]. Use csv.writer and writerows. Include file closure.

Show answer

One valid solution:

Python
import csv
with open('books.csv','w',newline='',encoding='utf-8') as f:
    w = csv.writer(f)
    w.writerow(['BookID','Title','Price'])
    w.writerows([[101,'Python',450],[102,'SQL',380]])
U1-294 marksImportant

Read books.csv from U1-28 and append only records with Price >= 400 to costly.csv. Do not copy the header. Convert the CSV price field to a number before comparing.

Show answer

One valid solution:

Python
import csv
with open('books.csv','r',newline='',encoding='utf-8') as src:
    with open('costly.csv','a',newline='',encoding='utf-8') as dst:
        rows = csv.reader(src)
        next(rows,None)
        w = csv.writer(dst)
        for row in rows:
            if row and float(row[2]) >= 400:
                w.writerow(row)
U1-304 marksImportant

Define append_student(filename,roll,name,marks) to append the list [roll,name,marks] as one pickled record to a binary file. Define create_empty(filename) to create/truncate a binary file.

Show answer

One valid solution:

Python
import pickle
def append_student(filename,roll,name,marks):
    with open(filename,'ab') as f:
        pickle.dump([roll,name,marks],f)

def create_empty(filename):
    with open(filename,'wb'):
        pass
U1-314 marksImportant

A trusted binary file stores consecutive pickled [roll,name,marks] records with unique rolls. Define find_student(filename,target) to return the matching record, or None if absent. Handle normal end-of-file.

Show answer

One valid solution:

Python
import pickle
def find_student(filename,target):
    with open(filename,'rb') as f:
        while True:
            try:
                rec = pickle.load(f)
            except EOFError:
                return None
            if rec[0] == target:
                return rec
U1-325 marksImportant

For the file format in U1-31, define update_marks(filename,target,newmarks) to update the matching unique roll, preserving all other records. Return True if found, else False. Read records before reopening for writing.

Show answer

A read-then-rewrite solution avoids assuming equal pickle record sizes:

Python
import pickle
def update_marks(filename,target,newmarks):
    records = []
    found = False
    with open(filename,'rb') as f:
        while True:
            try:
                rec = pickle.load(f)
            except EOFError:
                break
            if rec[0] == target:
                rec[2] = newmarks
                found = True
            records.append(rec)
    if found:
        with open(filename,'wb') as f:
            for rec in records:
                pickle.dump(rec,f)
    return found
U1-334 marksImportant

Define count_pass(filename) for the same binary format to count records with marks >= 33. Handle normal EOF and return the count.

Show answer

One valid solution:

Python
import pickle
def count_pass(filename):
    count = 0
    with open(filename,'rb') as f:
        while True:
            try:
                rec = pickle.load(f)
            except EOFError:
                break
            if rec[2] >= 33:
                count += 1
    return count
U1-343 marksImportant

Trace the function and write its output.

Python
def build(s):
    result = []
    for ch in s:
        if ch.isdigit():
            result.reverse()
        elif ch not in result:
            result.append(ch)
    return ''.join(result)
print(build('ab2ac3'))
Show answer

cab.

U1-353 marks

Write a program that reads two integer inputs and prints their quotient. Handle non-integer input and division by zero separately. Always print Done using finally.

Show answer

One valid solution:

Python
try:
    a = int(input('First integer: '))
    b = int(input('Second integer: '))
    print(a/b)
except ValueError:
    print('Enter integers only')
except ZeroDivisionError:
    print('Divisor cannot be zero')
finally:
    print('Done')
U1-363 marks

For a text file, distinguish read(), readline() and readlines(). Explain what writelines() does with ["Red","Blue"] and why a with block is useful.

Show answer

read() returns remaining text; readline() reads one line; readlines() returns remaining lines as a list. writelines(['Red','Blue']) writes RedBlue, adding no separators. A with block closes the file on exit, including when an exception occurs.

Part B – Previous year board questions (Unit 1)

CBSE Board Paper 2026 – 22 questions

Board 2026 · Q1
CBSE 2026 Class 12 CS board question Q1, Unit 1 Computational Thinking and Programming – 2
Show answer

False – 74 is int and 74.0 is float.

Board 2026 · Q2
CBSE 2026 Class 12 CS board question Q2, Unit 1 Computational Thinking and Programming – 2
Show answer

(A) The truth

Board 2026 · Q3
CBSE 2026 Class 12 CS board question Q3, Unit 1 Computational Thinking and Programming – 2
Show answer

(C) 3>1 and 3>2 – it gives True. (B) gives 2, not True.

Board 2026 · Q4
CBSE 2026 Class 12 CS board question Q4, Unit 1 Computational Thinking and Programming – 2
Show answer

(A) ('War and Peace ', 'by', ' Leo Tolstoy')

Board 2026 · Q5
CBSE 2026 Class 12 CS board question Q5, Unit 1 Computational Thinking and Programming – 2
Show answer

mroPo

Board 2026 · Q6
CBSE 2026 Class 12 CS board question Q6, Unit 1 Computational Thinking and Programming – 2
Show answer

(C) ('t', 'u', 'p', 'l', 'e', 'p') – t2 = t[2], is a one-element tuple ('p',).

Board 2026 · Q7
CBSE 2026 Class 12 CS board question Q7, Unit 1 Computational Thinking and Programming – 2
Show answer

(B) A dictionary cannot have two elements with same key.

Board 2026 · Q8
CBSE 2026 Class 12 CS board question Q8, Unit 1 Computational Thinking and Programming – 2
Show answer

(B) L.pop(6) – valid indexes are 0 to 5, so IndexError. (insert never raises IndexError.)

Board 2026 · Q9
CBSE 2026 Class 12 CS board question Q9, Unit 1 Computational Thinking and Programming – 2
Show answer

(C) 3-None – f1 prints 3- and returns None, which is then printed.

Board 2026 · Q10
CBSE 2026 Class 12 CS board question Q10, Unit 1 Computational Thinking and Programming – 2
Show answer

(B) rb

Board 2026 · Q11
CBSE 2026 Class 12 CS board question Q11, Unit 1 Computational Thinking and Programming – 2
Show answer

False – try-except handles run-time errors (exceptions), not logical errors.

Board 2026 · Q20
CBSE 2026 Class 12 CS board question Q20, Unit 1 Computational Thinking and Programming – 2
Show answer

(A) – both are true and the reason explains the assertion (TypeError: can only concatenate list to list).

Board 2026 · Q22
CBSE 2026 Class 12 CS board question Q22, Unit 1 Computational Thinking and Programming – 2
Show answer

Positional parameters get values according to their position in the call and must be given. Default parameters have a value in the function header, which is used when no argument is passed; they must come after the positional (non-default) parameters.

Python
def bill(price, qty=1):     # price: positional, qty: default
    return price * qty
Board 2026 · Q23
CBSE 2026 Class 12 CS board question Q23, Unit 1 Computational Thinking and Programming – 2
Show answer
Python
L1 = sorted(L)       # (i)
ch.isalnum()         # (ii) True if ch is an alphabet or a digit
Board 2026 · Q24
CBSE 2026 Class 12 CS board question Q24, Unit 1 Computational Thinking and Programming – 2
Show answer

(i) (a) 'RNo' in D1 OR (b) 12 in D1.values()

(ii) (a) D1.setdefault('RNo', 12) OR (b) D1.clear()

Board 2026 · Q25
CBSE 2026 Class 12 CS board question Q25, Unit 1 Computational Thinking and Programming – 2
Show answer

Option (D) 5-1-2-4- can NOT be displayed. The loop runs 4 times (i = 0, 1, 2, 3).

In the 2nd iteration j = randrange(1,5) is 1 to 4, so a[j] is 2 to 5 – it can never be 1. Options A, B and C are possible.

Board 2026 · Q26
CBSE 2026 Class 12 CS board question Q26, Unit 1 Computational Thinking and Programming – 2
Show answer

Corrections: iterate over s (not range(s)), test ch in 'aeiouAEIOU', c += 1, return c.

Python
def CountVowels(s):
    c = 0
    for ch in s:
        if ch in 'aeiouAEIOU':
            c += 1
    return c
Board 2026 · Q29
CBSE 2026 Class 12 CS board question Q29, Unit 1 Computational Thinking and Programming – 2
Show answer

(a)

Python
def count_digits():
    count = 0
    with open('Space.txt', 'r') as f:
        for ch in f.read():
            if ch.isdigit():
                count += 1
    return count

OR (b)

Python
def show_e_words():
    with open('Space.txt', 'r') as f:
        for word in f.read().split():
            if word.count('e') >= 2:
                print(word, end=' ')
Board 2026 · Q30
CBSE 2026 Class 12 CS board question Q30, Unit 1 Computational Thinking and Programming – 2
Show answer

(a)

Python
def push_fruit(FruitStack, Fruit):
    if Fruit['Price'] < 100:
        FruitStack.append(Fruit)

def pop_fruit(FruitStack):
    if FruitStack == []:
        print("UNDERFLOW")
        return None
    return FruitStack.pop()

def display(FruitStack):
    if FruitStack == []:
        print("EMPTY STACK")
    else:
        for rec in FruitStack[::-1]:
            print(rec)

OR (b)

Python
stack = []
for i in range(10):
    n = int(input("Enter an integer: "))
    if 100 <= abs(n) <= 999 and n % 2 == 0:
        stack.append(n)
while stack:
    print(stack.pop(), end=' ')
Board 2026 · Q31
CBSE 2026 Class 12 CS board question Q31, Unit 1 Computational Thinking and Programming – 2 (part 1)CBSE 2026 Class 12 CS board question Q31, Unit 1 Computational Thinking and Programming – 2 (part 2)
Show answer

(a)

Output
['4', '2', '-', 'd', 'l', 'o']

OR (b)

Output
1-6-10-13-15-16-
Board 2026 · Q33
CBSE 2026 Class 12 CS board question Q33, Unit 1 Computational Thinking and Programming – 2
Show answer
Python
import csv
with open('States.csv', 'r', newline='') as fin, open('More.csv', 'a', newline='') as fout:
    reader = csv.reader(fin)
    writer = csv.writer(fout)
    next(reader)                      # skip the header row
    for rec in reader:
        if int(rec[2]) > 10000000:
            writer.writerow(rec)
Board 2026 · Q36
CBSE 2026 Class 12 CS board question Q36, Unit 1 Computational Thinking and Programming – 2
Show answer
Python
import pickle

def Append():
    rid = int(input("Resource person ID: "))
    name = input("Name: ")
    exp = input("Expertise: ")
    charges = int(input("Charges per hour: "))
    with open('RESOURCES.DAT', 'ab') as f:
        pickle.dump((rid, name, exp, charges), f)

def Update():
    records = []
    with open('RESOURCES.DAT', 'rb') as f:
        while True:
            try:
                records.append(pickle.load(f))
            except EOFError:
                break
    with open('RESOURCES.DAT', 'wb') as f:
        for r in records:            # tuples are immutable, so make a new tuple
            pickle.dump((r[0], r[1], r[2], r[3] + 500), f)

CBSE Board Paper 2023 – 23 questions

Board 2023 · Q1
CBSE 2023 Class 12 CS board question Q1, Unit 1 Computational Thinking and Programming – 2
Show answer

True

Board 2023 · Q2
CBSE 2023 Class 12 CS board question Q2, Unit 1 Computational Thinking and Programming – 2
Show answer

(b) return

Board 2023 · Q3
CBSE 2023 Class 12 CS board question Q3, Unit 1 Computational Thinking and Programming – 2
Show answer

(b) Tup.insert(2,3) – a tuple is immutable and has no insert() method.

Board 2023 · Q4
CBSE 2023 Class 12 CS board question Q4, Unit 1 Computational Thinking and Programming – 2
Show answer

(a) True

Board 2023 · Q5
CBSE 2023 Class 12 CS board question Q5, Unit 1 Computational Thinking and Programming – 2
Show answer

(d) – partition(' ') splits at the first space: ('Amrit', ' ', 'Mahotsav @ 75'). The middle element is the separator (a space).

Board 2023 · Q6
CBSE 2023 Class 12 CS board question Q6, Unit 1 Computational Thinking and Programming – 2
Show answer

(d) a

Board 2023 · Q7
CBSE 2023 Class 12 CS board question Q7, Unit 1 Computational Thinking and Programming – 2
Show answer

(a) sort()

Board 2023 · Q8
CBSE 2023 Class 12 CS board question Q8, Unit 1 Computational Thinking and Programming – 2
Show answer

(b) !=

Board 2023 · Q9
CBSE 2023 Class 12 CS board question Q9, Unit 1 Computational Thinking and Programming – 2
Show answer

(d) Statements 2 and 4 – Stud[95] raises KeyError (95 is a value, not a key) and dict.pop() needs a key argument.

Board 2023 · Q11
CBSE 2023 Class 12 CS board question Q11, Unit 1 Computational Thinking and Programming – 2
Show answer

(a) 0 (beginning of the file)

Board 2023 · Q14
CBSE 2023 Class 12 CS board question Q14, Unit 1 Computational Thinking and Programming – 2
Show answer

(b) 8.0 – 3*5/3 = 5.0, 5%2 = 1, so 4 + 5.0 - 1 = 8.0

Board 2023 · Q15
CBSE 2023 Class 12 CS board question Q15, Unit 1 Computational Thinking and Programming – 2
Show answer

(b) sum()

Board 2023 · Q17
CBSE 2023 Class 12 CS board question Q17, Unit 1 Computational Thinking and Programming – 2
Show answer

(b) – both are true, but the reason (where import can be written) is not the explanation of why we must import.

Board 2023 · Q18
CBSE 2023 Class 12 CS board question Q18, Unit 1 Computational Thinking and Programming – 2
Show answer

(a) – both are true and the reason explains LIFO: a new element always goes on top (after the last element), so it is the first to be removed.

Board 2023 · Q19
CBSE 2023 Class 12 CS board question Q19, Unit 1 Computational Thinking and Programming – 2
Show answer

Corrections: L[0] instead of L(0), colon after if, indentation of max=a.

Python
def max_num(L):
    max = L[0]
    for a in L:
        if a > max:
            max = a
    return max
Board 2023 · Q21
CBSE 2023 Class 12 CS board question Q21, Unit 1 Computational Thinking and Programming – 2
Show answer

(a) ['Rajat', 'Rajan', 'Ashish'] (b) 1

Board 2023 · Q24
CBSE 2023 Class 12 CS board question Q24, Unit 1 Computational Thinking and Programming – 2 (part 1)CBSE 2023 Class 12 CS board question Q24, Unit 1 Computational Thinking and Programming – 2 (part 2)
Show answer

(a)

Output
['CSCS', 'HINDIHINDI', 'PHYSICSPHYSICS', 'CHEMISTRYCHEMISTRY', 'MATHSMATHS']

OR (b) a = 30 is even, so x += a each time: 35+30 = 65 and 40+30 = 70.

Output
65#70@
Board 2023 · Q27
CBSE 2023 Class 12 CS board question Q27, Unit 1 Computational Thinking and Programming – 2 (part 1)CBSE 2023 Class 12 CS board question Q27, Unit 1 Computational Thinking and Programming – 2 (part 2)
Show answer

(a)

Python
def LongLines():
    with open('LINES.TXT', 'r') as f:
        for line in f:
            if len(line.split()) >= 10:
                print(line, end='')

OR (b)

Python
def count_Dwords():
    count = 0
    with open('Details.txt', 'r') as f:
        for word in f.read().split():
            if word[-1].isdigit():
                count += 1
    print("Number of words ending with a digit are", count)
Board 2023 · Q29
CBSE 2023 Class 12 CS board question Q29, Unit 1 Computational Thinking and Programming – 2
Show answer
Python
def EOReplace(L):
    for i in range(len(L)):
        if L[i] % 2 == 0:
            L[i] = L[i] + 1
        else:
            L[i] = L[i] - 1
    print(L)
Board 2023 · Q30
CBSE 2023 Class 12 CS board question Q30, Unit 1 Computational Thinking and Programming – 2
Show answer

(a)

Python
Hotel = []

def Push_Cust(customers):
    for rec in customers:
        if rec[1] == 'Delux':
            Hotel.append(rec[0])

def Pop_Cust():
    while Hotel:
        print(Hotel.pop())
    print("Underflow")

OR (b)

Python
stack = []

def Push(Vehicle):
    for car, maker in Vehicle.items():
        if maker.upper() == 'TATA':
            stack.append(car)
Board 2023 · Q32(a)
CBSE 2023 Class 12 CS board question Q32(a), Unit 1 Computational Thinking and Programming – 2 (part 1)CBSE 2023 Class 12 CS board question Q32(a), Unit 1 Computational Thinking and Programming – 2 (part 2)
Show answer

Possible output: (i) only.

first = randint(2,5) - 1 gives 1 to 4, sec = randint(3,6) - 2 gives 1 to 4, third = randint(1,4) gives 1 to 4, so every value is M[1]…M[4] = 10, 15, 20 or 25 (never 5 or 30), and sep='#' puts # only between values (no # at the end).

Alternative (a) – makenew("No@1"):

Output
N1@3

(count 0 → 'N'; count 1 → '1'; count 2 → '@'.upper() = '@'; count 3 → '3')

Board 2023 · Q33
CBSE 2023 Class 12 CS board question Q33, Unit 1 Computational Thinking and Programming – 2
Show answer

(a) A text file stores plain lines of text; a CSV file is a text file in which each line is a record and values are separated by commas (tabular data, opened with the csv module).

Python
import csv

def COURIER_ADD():
    with open('courier.csv', 'a', newline='') as f:
        w = csv.writer(f)
        cid = input("Courier ID: ")
        s_name = input("Sender name: ")
        source = input("Source: ")
        destination = input("Destination: ")
        w.writerow([cid, s_name, source, destination])

def COURIER_SEARCH():
    dest = input("Destination to search: ")
    with open('courier.csv', 'r', newline='') as f:
        for rec in csv.reader(f):
            if rec[3] == dest:
                print(rec)

COURIER_ADD()
COURIER_SEARCH()

OR (b) A file should be closed so that all data in the buffer is written to the disk, the resources are freed and the data is not lost or corrupted.

Python
import csv

def Add_Book():
    with open('Book.csv', 'a', newline='') as f:
        w = csv.writer(f)
        book_ID = input("Book ID: ")
        B_name = input("Book name: ")
        pub = input("Publisher: ")
        w.writerow([book_ID, B_name, pub])

def Search_Book():
    p = input("Publisher name: ")
    count = 0
    with open('Book.csv', 'r', newline='') as f:
        for rec in csv.reader(f):
            if rec[2] == p:
                count += 1
    print("Number of books published by", p, "=", count)

Add_Book()
Search_Book()
Board 2023 · Q35
CBSE 2023 Class 12 CS board question Q35, Unit 1 Computational Thinking and Programming – 2
Show answer

(i) Statement 1: bin_file = open('Cust_file.dat', 'wb') (or 'ab' to keep old records)

(ii) Statement 2: if qty < 10:

(iii) Statement 3: pickle.dump(c_detail, bin_file) Statement 4: break

OR (iii) Statement 5: bin_file.close() Statement 6: write_bin()

CBSE Board Paper 2022 (Term-2, 35 marks) – 2 questions

Board 2022 · Q1
CBSE 2022 Class 12 CS board question Q1, Unit 1 Computational Thinking and Programming – 2
Show answer

A stack follows LIFO (Last In, First Out) – the element added last is removed first. The list method pop() removes the last element.

Python
stack = [10, 20, 30]
stack.pop()        # removes 30
print(stack)       # [10, 20]
Board 2022 · Q8
CBSE 2022 Class 12 CS board question Q8, Unit 1 Computational Thinking and Programming – 2 (part 1)CBSE 2022 Class 12 CS board question Q8, Unit 1 Computational Thinking and Programming – 2 (part 2)
Show answer
Python
def PushNV(N):
    for word in N:
        for ch in word:
            if ch in 'aeiouAEIOU':
                break
        else:                       # no vowel found
            NoVowel.append(word)

All = []
NoVowel = []
for i in range(5):
    All.append(input("Enter a word: "))
PushNV(All)
while NoVowel:
    print(NoVowel.pop(), end=' ')
print("EmptyStack")

OR

Python
def Push3_5(N):
    for x in N:
        if x % 3 == 0 or x % 5 == 0:
            Only3_5.append(x)

NUM = []
Only3_5 = []
for i in range(5):
    NUM.append(int(input("Enter an integer: ")))
Push3_5(NUM)
while Only3_5:
    print(Only3_5.pop(), end=' ')
print("StackEmpty")
Next

Next: Unit 2 – Networks: Evolution & Types.

← Class 12 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicNetworks: Evolution & Types Your progress: 10 / 24 (42%) · Lesson 11 / 24 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free