Class XII Computer Science (083)

Minimum Learning Support Material · CBSE 2026-27

Notes · Code templates · 1131 solved questions · Flashcards · Quiz · Practice Paper Maker

Designed by NareN, PGT (Computer Science), PM SHRI K V Shalimar Bagh, Delhi-88 (Shift-I) ✨ Click Here For Your Valuable Feedback ✨
1

Know the paper first

Same design in the CBSE Sample Paper 2026-27 as in the 2025 and 2026 board papers

SectionQuestionsMarks eachTotalWhat comes
AQ1 to Q21121MCQ, True/False, output, full forms. Q20 and Q21 are Assertion-Reason.
BQ22 to Q28214Short theory, built-in functions, error correction, SQL commands, network terms
CQ29 to Q3139Text file, Stack, output or function writing
DQ32 to Q35416SQL queries, CSV file, two-table SQL, Python-MySQL
EQ36, Q37510Binary file, Networking case study

The fixed slots: 36 marks you can predict

In all three papers studied (CBSE 2025, CBSE 2026, Sample Paper 2026-27) these question numbers carried the same topic. Prepare one template for each slot.

Q27SQL commands / constraints2 marks
Q28Network short answer2 marks
Q29Text file function3 marks
Q30Stack push / pop3 marks
Q32SQL queries, one table4 marks
Q33CSV file functions4 marks
Q34SQL on two tables (join)4 marks
Q35Python-MySQL program4 marks
Q36Binary file (pickle)5 marks
Q37Network case study5 marks

Practical: 30 marks

2

Pass plan in three steps

A suggested order of study for a student starting late. Pass mark is 33%, about 23 of 70 in theory.

25+STEP 1 · SAFE PASS
Networks + SQL first. Q37 case study (5), Q28 (2), Q32 and Q34 SQL queries (8), Q27 (2), plus the network and database one-markers. No programming logic needed, only rules and syntax.
45+STEP 2 · FIRST DIVISION
Add the four templates. Stack (3), text file (3), CSV (4), binary file (5), Python-MySQL (4). Learn the skeleton by heart, then change only the condition.
60+STEP 3 · DISTINCTION
Add output and error questions. String slicing, operator precedence, list and dictionary methods, random module, scope of variables. Practise by tracing with pen and paper.
RememberMarks are given step by step. Even a half-correct program earns marks for import, opening the file, the loop and closing the file. Never leave a programming question blank.
3

Python revision and functions

Unit 1 · feeds most of Section A and Section B

Building blocks of a program (tokens)

A token is the smallest meaningful unit of a program. Python has five kinds of tokens.

TokenMeaningExamples
KeywordA reserved word with a fixed meaningif else for while def return import True None break
IdentifierA name given by the programmer to a variable or functionmarks roll_no Total2
LiteralA fixed value written in the program25 3.14 "KV" True
OperatorA symbol that calculates or compares+ - * / // % ** == != > < and or not in is
PunctuatorA symbol that organises the code( ) [ ] { } : , . #

Rules for identifiers

  • Use letters, digits and underscore only.
  • Do not start with a digit.
  • No spaces and no special symbols.
  • A keyword cannot be used as a name.
  • Capital and small letters are different: Marks is not marks.

Check yourself

Valid: roll_no _x Total2 Break

Invalid: 2total roll-no my name for

Data types and type conversion

TypeHoldsExample
intwhole numbers25 -7
floatnumbers with a decimal point3.14 74.0
booltruth valuesTrue False
strtext inside quotes"KV" 'XII'
listmany values, can be changed[10, "a", 2.5]
tuplemany values, cannot be changed(10, 20) and (5,) for one value
dictkey : value pairs{"RNo": 12, "Name": "Asha"}
Noneno valueNone

Implicit conversion

Python changes the type by itself, without loss of data.

5 + 2.5 gives 7.5 (int becomes float).

Explicit conversion (type casting)

The programmer changes the type with a function.

int("25") → 25 · float(7) → 7.0 · str(25) → "25" · list("abc") → ['a', 'b', 'c']

Three kinds of errors

ErrorWhat happensExample
Syntax errorA rule of the language is broken. The program does not start.missing colon, missing bracket
Run-time error (exception)The program starts but stops in the middle.10 / 0, int("abc")
Logical errorThe program runs fully but the answer is wrong.writing a + b where a * b was needed

Decisions and loops

marks = 72
if marks >= 75:
    print("Distinction")
elif marks >= 33:
    print("Pass")           # this line runs
else:
    print("Needs improvement")
for i in range(1, 6):       # 1 2 3 4 5
    if i == 2:
        continue            # skip this round
    if i == 5:
        break               # leave the loop
    print(i)                # prints 1 3 4

n = 3
while n > 0:                # repeats while condition is True
    n -= 1

range(start, stop, step)

  • range(5) → 0, 1, 2, 3, 4 (stop is not included)
  • range(2, 6) → 2, 3, 4, 5
  • range(10, 0, -2) → 10, 8, 6, 4, 2

Picture: how a decision is taken

An if statement asks a yes/no question. If the answer is yes, its block runs. If not, Python tries the next elif. When nothing is true, the else block runs.

Startmarks >= 75 ?YesDistinctionNomarks >= 33 ?YesPassNoNeeds improvementEnd
Only one branch runs. Python checks from the top and stops at the first true condition.

In daily life: At a traffic signal: if the light is green, go; else if it is yellow, slow down; else stop.

Picture: how a loop repeats

A loop runs the same block again and again. A for loop takes values one by one from a sequence. A while loop repeats as long as its condition is true.

for i in range(1, 6)any value left ?Yesrun the loop bodyNoExitcontinue: go back to the check at oncebreak: go straight to Exit
The body repeats while values are left. break leaves the loop; continue jumps back to the check.

In daily life: The school bell rings for every period: the same action repeats until the periods are over.

Four collections compared

FeatureStringListTupleDictionary
Written in" "[ ]( ){ }
Can be changed?NoYesNoYes
Reached byindexindexindexkey
Example"KVS"[1, 2, 3](1, 2, 3){"a": 1}

Picture: a list is a row of numbered boxes

Every item of a list sits in a box with an index number. Counting starts from 0 on the left. From the right, counting starts from -1.

L = [10, 20, 30, 40]

010-4
120-3
230-2
340-1

L[1] and L[-3] are the same box: 20.

In daily life: Seats in a row of the hall: seat number tells you exactly where a student sits.

Picture: a dictionary is a set of labelled lockers

A dictionary does not use index numbers. Every value has its own label, called the key. You open a locker by its key.

D = {"RNo": 12, "Name": "Asha", "Marks": 91}

"RNo"12
"Name"Asha
"Marks"91

D["Name"] gives Asha. Keys cannot repeat; values can.

In daily life: A contact list on a phone: you search by the name (key) and get the number (value).

Operator precedence (high to low)

( )>**>+x -x>* / // %>+ ->< > == != in is>not>and>or
Remember** works right to left: 2**3**2 = 2**9 = 512. / always gives float, // of two ints gives int.

Worked board examples

  • 14 % 3 ** 2 * 4 → 14 % 9 = 5, then 5 * 4 = 20
  • 25 + 100**1**3 / 5 → 100 / 5 = 20.0, answer 45.0

Mutable or immutable

Mutable (can change in place)

list dict set

A list passed to a function can be changed by the function.

Immutable (cannot change)

int float bool str tuple

t[0] = 5 on a tuple or string gives TypeError. tuple + list also gives TypeError.

Picture: mutable and immutable

List: the same box changes

L = [1, 2, 3]

1
2
3

L.append(4)

1
2
3
4

Same object, now longer. So a list is mutable.

String: a new box is made

s = "KV"

K
V

s = s + "S"

K
V
S

A brand-new string is created. The old one cannot be changed, so a string is immutable.

In daily life: Writing with a pencil (you can rub and change) and writing with a pen (to change, you write again on a new page).

Slicing: s[start : stop : step]

Picture: index numbers of a string

s = "PYTHON"

0P-6
1Y-5
2T-4
3H-3
4O-2
5N-1

s[1:4] picks the boxes 1, 2 and 3: YTH. The stop index 4 is not included.

s[-1] is the last letter N. s[::-1] reads the boxes from right to left: NOHTYP.

Stop is never included. Negative step moves right to left. Write the index numbers above the letters and walk.

  • "PythonProgram"[-1:2:-2] → start at m (12), jump 2 backwards, stop before index 2 → mroPo
  • "Drone Expo"[-2::-4] → p (8), e (4), D (0) → peD
  • L[::-1] reverses any list or string.

Try it Slicing lab

Leave a box empty to use the default. Coloured cells are picked; the small number shows the order.

Methods asked again and again

TypeMethodResult
String"the Truth".capitalize()'The truth' (first capital, rest small)
s.find(x) / s.index(x)position; not found gives -1 / ValueError
s.split('m')list of parts, separator removed
s.partition("by")always a tuple of 3: (before, "by", after)
isalpha() isdigit() isalnum() isupper()True or False
startswith() endswith() count() replace()check / count / new string
ListL.append(x) / L.extend([..])add one item / add many items
L.insert(i, x)put x at index i
L.pop() / L.pop(i) / L.remove(x)delete last / by index / by value. Wrong index gives IndexError.
L.sort() vs sorted(L)changes L / returns a new sorted list
DictionaryD.get(k)value, or None if key is missing (no error)
k in D / v in D.values()check key / check value
D.setdefault(k, v)adds k only if missing, returns the value
D.update(D2) D.pop(k) D.clear()merge / delete one / delete all

Functions with examples: strings, lists, tuples, dictionaries

Every function below has three examples. The line after >>> is what you type; the green line is what Python gives back. Tap a heading to open it.

String functions26 functions · 3 examples each
len(s)counts the characters, spaces included
>>> len("Python")
6

>>> len("KV Delhi")
8

>>> len("")
0
s.capitalize()first letter capital, all others small
>>> "hello world".capitalize()
'Hello world'

>>> "PYTHON".capitalize()
'Python'

>>> "the Truth".capitalize()
'The truth'
s.title()first letter of every word capital
>>> "hello world".title()
'Hello World'

>>> "kendriya vidyalaya".title()
'Kendriya Vidyalaya'

>>> "pYTHON is FUN".title()
'Python Is Fun'
s.lower()all letters small
>>> "HELLO".lower()
'hello'

>>> "Python 3".lower()
'python 3'

>>> "KvS".lower()
'kvs'
s.upper()all letters capital
>>> "hello".upper()
'HELLO'

>>> "Python 3".upper()
'PYTHON 3'

>>> "kvs delhi".upper()
'KVS DELHI'
s.count(x)how many times x comes in s
>>> "banana".count("a")
3

>>> "banana".count("an")
2

>>> "banana".count("x")
0
s.find(x)position of x; gives -1 when x is not there
>>> "computer".find("put")
3

>>> "computer".find("z")
-1

>>> "banana".find("a", 2)
3
s.index(x)position of x; gives an error when x is not there
>>> "computer".index("m")
2

>>> "banana".index("na")
2

>>> "computer".index("z")
ValueError: substring not found
s.startswith(x)True if s begins with x
>>> "Python".startswith("Py")
True

>>> "Python".startswith("py")
False

>>> "admin_01".startswith("admin")
True
s.endswith(x)True if s ends with x
>>> "notes.txt".endswith(".txt")
True

>>> "notes.txt".endswith(".csv")
False

>>> "Delhi".endswith("i")
True
s.isalnum()True if s has only letters and digits
>>> "Class12".isalnum()
True

>>> "Class 12".isalnum()
False

>>> "12".isalnum()
True
s.isalpha()True if s has only letters
>>> "Python".isalpha()
True

>>> "Python3".isalpha()
False

>>> "KV Delhi".isalpha()
False
s.isdigit()True if s has only digits
>>> "2027".isdigit()
True

>>> "20.27".isdigit()
False

>>> "XII".isdigit()
False
s.islower()True if all the letters are small
>>> "python".islower()
True

>>> "Python".islower()
False

>>> "python3".islower()
True
s.isupper()True if all the letters are capital
>>> "CBSE".isupper()
True

>>> "Cbse".isupper()
False

>>> "CBSE 2027".isupper()
True
s.isspace()True if s has only spaces
>>> "   ".isspace()
True

>>> " a ".isspace()
False

>>> "".isspace()
False
s.lstrip()removes spaces (or given letters) from the left side
>>> "   hello  ".lstrip()
'hello  '

>>> "xxhixx".lstrip("x")
'hixx'

>>> "hello".lstrip()
'hello'
s.rstrip()removes spaces (or given letters) from the right side
>>> "   hello  ".rstrip()
'   hello'

>>> "xxhixx".rstrip("x")
'xxhi'

>>> "data\n".rstrip()
'data'
s.strip()removes spaces (or given letters) from both sides
>>> "   hello  ".strip()
'hello'

>>> "xxhixx".strip("x")
'hi'

>>> "\n data \n".strip()
'data'
s.replace(old, new)changes every old part into new
>>> "banana".replace("a", "o")
'bonono'

>>> "I like tea".replace("tea", "milk")
'I like milk'

>>> "aaa".replace("a", "b", 2)
'bba'
x.join(list)joins the strings of a list, putting x between them
>>> "-".join(["a", "b", "c"])
'a-b-c'

>>> " ".join(["XII", "CS"])
'XII CS'

>>> "".join(["K", "V", "S"])
'KVS'
s.partition(x)breaks s into 3 parts: before x, x, after x
>>> "War and Peace".partition("and")
('War ', 'and', ' Peace')

>>> "name=Asha".partition("=")
('name', '=', 'Asha')

>>> "hello".partition("x")
('hello', '', '')
s.split(x)breaks s into a list at every x (at spaces if x is not given)
>>> "a b c".split()
['a', 'b', 'c']

>>> "a,b,c".split(",")
['a', 'b', 'c']

>>> "2027-03-15".split("-")
['2027', '03', '15']
s1 + s2joins two strings
>>> "KV" + "S"
'KVS'

>>> "Class " + "XII"
'Class XII'

>>> "5" + "5"
'55'
s * nrepeats the string n times
>>> "ab" * 3
'ababab'

>>> "-" * 10
'----------'

>>> "Hi" * 0
''
x in sTrue if x is found inside s
>>> "th" in "Python"
True

>>> "TH" in "Python"
False

>>> "z" not in "Python"
True
List functions15 functions · 3 examples each
len(L)counts the elements
>>> len([10, 20, 30])
3

>>> len([])
0

>>> len([[1, 2], [3]])
2
list(x)makes a list out of a string, tuple or range
>>> list("abc")
['a', 'b', 'c']

>>> list((1, 2, 3))
[1, 2, 3]

>>> list(range(4))
[0, 1, 2, 3]
L.append(x)adds x as ONE element at the end
>>> L = [1, 2]
>>> L.append(3)
>>> L
[1, 2, 3]

>>> L = []
>>> L.append("a")
>>> L
['a']

>>> L = [1, 2]
>>> L.append([3, 4])
>>> L
[1, 2, [3, 4]]
L.extend(seq)adds EVERY element of seq at the end
>>> L = [1, 2]
>>> L.extend([3, 4])
>>> L
[1, 2, 3, 4]

>>> L = ["a"]
>>> L.extend("bc")
>>> L
['a', 'b', 'c']

>>> L = [1]
>>> L.extend((2, 3))
>>> L
[1, 2, 3]
L.insert(i, x)puts x at index i; the others shift right
>>> L = [10, 30]
>>> L.insert(1, 20)
>>> L
[10, 20, 30]

>>> L = [1, 2]
>>> L.insert(0, 0)
>>> L
[0, 1, 2]

>>> L = [1, 2]
>>> L.insert(10, 9)
>>> L
[1, 2, 9]
L.count(x)how many times x comes in the list
>>> [1, 2, 2, 3, 2].count(2)
3

>>> ["a", "b"].count("z")
0

>>> [1, [1], 1].count(1)
2
L.index(x)position of the first x; error if x is not there
>>> [10, 20, 30].index(20)
1

>>> ["a", "b", "a"].index("a")
0

>>> [10, 20].index(50)
ValueError: 50 is not in list
L.remove(x)removes the first x (by value); error if x is not there
>>> L = [1, 2, 3, 2]
>>> L.remove(2)
>>> L
[1, 3, 2]

>>> L = ["a", "b"]
>>> L.remove("a")
>>> L
['b']

>>> L = [1, 2]
>>> L.remove(5)
ValueError: list.remove(x): x not in list
L.pop(i)removes and gives back the element at index i (the last one if i is not given)
>>> L = [10, 20, 30]
>>> x = L.pop()
>>> x, L
(30, [10, 20])

>>> L = [10, 20, 30]
>>> x = L.pop(0)
>>> x, L
(10, [20, 30])

>>> L = []
>>> L.pop()
IndexError: pop from empty list
L.reverse()turns the list back to front
>>> L = [1, 2, 3]
>>> L.reverse()
>>> L
[3, 2, 1]

>>> L = ["a", "b"]
>>> L.reverse()
>>> L
['b', 'a']

>>> L = [5]
>>> L.reverse()
>>> L
[5]
L.sort()arranges the list itself in order
>>> L = [3, 1, 2]
>>> L.sort()
>>> L
[1, 2, 3]

>>> L = [3, 1, 2]
>>> L.sort(reverse=True)
>>> L
[3, 2, 1]

>>> L = ["pear", "apple", "fig"]
>>> L.sort()
>>> L
['apple', 'fig', 'pear']
sorted(L)gives a NEW sorted list; L stays the same
>>> sorted([3, 1, 2])
[1, 2, 3]

>>> sorted("exam")
['a', 'e', 'm', 'x']

>>> L = [3, 1, 2]
>>> M = sorted(L, reverse=True)
>>> L, M
([3, 1, 2], [3, 2, 1])
min(L)the smallest element
>>> min([4, 9, 1])
1

>>> min(["pear", "apple"])
'apple'

>>> min([2.5, 2])
2
max(L)the largest element
>>> max([4, 9, 1])
9

>>> max(["pear", "apple"])
'pear'

>>> max([-3, -8])
-3
sum(L)adds all the numbers
>>> sum([4, 6, 10])
20

>>> sum([1.5, 2.5])
4.0

>>> sum([])
0
Tuple functions6 functions · 3 examples each
len(T)counts the elements
>>> len((1, 2, 3))
3

>>> len(())
0

>>> len((5,))
1
tuple(x)makes a tuple out of a list, string or range
>>> tuple([1, 2])
(1, 2)

>>> tuple("ab")
('a', 'b')

>>> tuple(range(3))
(0, 1, 2)
T.count(x)how many times x comes in the tuple
>>> (1, 2, 1, 1).count(1)
3

>>> ("a", "b").count("a")
1

>>> (1, 2).count(9)
0
T.index(x)position of the first x; error if x is not there
>>> (10, 20, 30).index(30)
2

>>> ("x", "y").index("x")
0

>>> (1, 2).index(5)
ValueError: tuple.index(x): x not in tuple
sorted(T)gives a sorted LIST of the elements
>>> sorted((3, 1, 2))
[1, 2, 3]

>>> sorted(("b", "a"))
['a', 'b']

>>> sorted((3, 1, 2), reverse=True)
[3, 2, 1]
min(T), max(T), sum(T)smallest, largest and total
>>> min((4, 9, 1))
1

>>> max((4, 9, 1))
9

>>> sum((4, 9, 1))
14
Dictionary functions17 functions · 3 examples each
len(D)counts the key : value pairs
>>> len({"a": 1, "b": 2})
2

>>> len({})
0

>>> len({1: "x", 2: "y", 3: "z"})
3
dict()makes a dictionary
>>> dict(a=1, b=2)
{'a': 1, 'b': 2}

>>> dict([("x", 10), ("y", 20)])
{'x': 10, 'y': 20}

>>> dict()
{}
D.keys()all the keys
>>> list({"a": 1, "b": 2}.keys())
['a', 'b']

>>> {"RNo": 1, "Name": "Asha"}.keys()
dict_keys(['RNo', 'Name'])

>>> list({}.keys())
[]
D.values()all the values
>>> list({"a": 1, "b": 2}.values())
[1, 2]

>>> {"RNo": 1, "Name": "Asha"}.values()
dict_values([1, 'Asha'])

>>> sum({"a": 1, "b": 2}.values())
3
D.items()all the (key, value) pairs
>>> list({"a": 1, "b": 2}.items())
[('a', 1), ('b', 2)]

>>> {"x": 5}.items()
dict_items([('x', 5)])

>>> len({"a": 1, "b": 2}.items())
2
D.get(k)value of key k; gives None (no error) when k is missing
>>> {"a": 1}.get("a")
1

>>> print({"a": 1}.get("z"))
None

>>> {"a": 1}.get("z", 0)
0
D[k]value of key k; error when k is missing
>>> {"a": 1, "b": 2}["b"]
2

>>> D = {"a": 1}
>>> D["c"] = 3
>>> D
{'a': 1, 'c': 3}

>>> {"a": 1}["z"]
KeyError: 'z'
D.update(D2)adds the pairs of D2; a key already present gets the new value
>>> D = {"a": 1}
>>> D.update({"b": 2})
>>> D
{'a': 1, 'b': 2}

>>> D = {"a": 1}
>>> D.update({"a": 9})
>>> D
{'a': 9}

>>> D = {}
>>> D.update(x=5)
>>> D
{'x': 5}
del D[k]deletes the pair with key k; error when k is missing
>>> D = {"a": 1, "b": 2}
>>> del D["a"]
>>> D
{'b': 2}

>>> D = {"x": 5}
>>> del D["x"]
>>> D
{}

>>> D = {"a": 1}
>>> del D["z"]
KeyError: 'z'
D.clear()removes everything
>>> D = {"a": 1}
>>> D.clear()
>>> D
{}

>>> D = {"a": 1, "b": 2}
>>> D.clear()
>>> len(D)
0

>>> D = {}
>>> D.clear()
>>> D
{}
dict.fromkeys(keys, v)new dictionary with the given keys, all having value v
>>> dict.fromkeys(["a", "b"], 0)
{'a': 0, 'b': 0}

>>> dict.fromkeys("xy")
{'x': None, 'y': None}

>>> dict.fromkeys([1, 2], "N")
{1: 'N', 2: 'N'}
D.copy()a separate copy; changing the copy does not change D
>>> D = {"a": 1}
>>> E = D.copy()
>>> E["b"] = 2
>>> D, E
({'a': 1}, {'a': 1, 'b': 2})

>>> D = {"a": 1}
>>> E = D
>>> E["b"] = 2
>>> D
{'a': 1, 'b': 2}

>>> {"x": 5}.copy()
{'x': 5}
D.pop(k)removes key k and gives back its value
>>> D = {"a": 1, "b": 2}
>>> x = D.pop("a")
>>> x, D
(1, {'b': 2})

>>> {"a": 1}.pop("z", 0)
0

>>> {"a": 1}.pop("z")
KeyError: 'z'
D.popitem()removes and gives back the pair that was added last
>>> D = {"a": 1, "b": 2}
>>> x = D.popitem()
>>> x, D
(('b', 2), {'a': 1})

>>> {"k": 9}.popitem()
('k', 9)

>>> {}.popitem()
KeyError: 'popitem(): dictionary is empty'
D.setdefault(k, v)adds k : v only if k is missing
>>> D = {"a": 1}
>>> D.setdefault("b", 2)
>>> D
{'a': 1, 'b': 2}

>>> D = {"a": 1}
>>> D.setdefault("a", 9)
>>> D
{'a': 1}

>>> D = {}
>>> D.setdefault("x")
>>> D
{'x': None}
max(D), min(D), sorted(D)these work on the KEYS
>>> max({"b": 1, "a": 5})
'b'

>>> sorted({"b": 1, "a": 5})
['a', 'b']

>>> max({"b": 1, "a": 5}.values())
5
k in DTrue if k is one of the KEYS
>>> "a" in {"a": 1}
True

>>> 1 in {"a": 1}
False

>>> 1 in {"a": 1}.values()
True
Other built-in functions6 functions · 3 examples each
int(x)changes x into a whole number
>>> int("25")
25

>>> int(7.9)
7

>>> int("abc")
ValueError: invalid literal for int() with base 10: 'abc'
float(x)changes x into a decimal number
>>> float(7)
7.0

>>> float("3.5")
3.5

>>> float("7") + 1
8.0
str(x)changes x into a string
>>> str(25)
'25'

>>> str(3.5) + "%"
'3.5%'

>>> str(25) + str(5)
'255'
type(x)tells the data type
>>> type(74)
<class 'int'>

>>> type(74.0)
<class 'float'>

>>> type([1, 2])
<class 'list'>
abs(x)the positive value
>>> abs(-7)
7

>>> abs(3.5)
3.5

>>> abs(0)
0
range(start, stop, step)a run of numbers; stop is not included
>>> list(range(5))
[0, 1, 2, 3, 4]

>>> list(range(2, 6))
[2, 3, 4, 5]

>>> list(range(10, 0, -3))
[10, 7, 4, 1]

Functions

A function is a named block of code that does one job. It is written once and can be called many times. Functions make a program shorter, easier to read and easier to correct.

Kind of functionWhere it comes fromExamples
Built-inalways available in Pythonprint() len() int() max() sorted()
Module functionavailable after importmath.sqrt() random.randint() statistics.mean()
User-definedwritten by the programmer with defdef area(l, b):

Parts of a function and flow of execution

  • Header: def name(parameters): ends with a colon.
  • Body: the indented statements below the header.
  • return: sends the result back. It is optional.
  • Call: name(arguments). A function does nothing until it is called.
  • Flow: Python starts from the first statement outside the functions. At a call, control jumps into the function, runs the body, and comes back to the line of the call.
def area(l, b=5):      # l positional, b default
    return l * b       # sends value back, ends function

print(area(4))         # 20  (b takes 5)
print(area(4, 2))      # 8
print(area(b=3, l=2))  # 6   keyword arguments
x = 10                 # global variable
def show():
    y = 5              # local variable
    print(x + y)

def change():
    global x           # allows changing the global
    x = x + 1

Rules

  • Default parameters go to the right of non-default ones.
  • A function without return returns None.
  • Global: made outside functions, usable everywhere. Local: made inside a function, usable only there.
Common mistakeAssigning to a global name inside a function without the global statement, then reading it first, gives UnboundLocalError. The sample paper asks exactly this.

Picture: what happens when a function is called

A function is like a small machine. You give it inputs (arguments), it does its work, and it gives back a result with return.

Main programa = area(4, 5)print(a) # 20Functiondef area(l, b):return l * b1 call2 return 204, 53 goes on
The call sends 4 and 5 to l and b. The function sends 20 back with return.

In daily life: A juice machine: put in fruit (arguments), the machine works (function body), and juice comes out (return value).

Picture: where a variable can be used

The place where a variable can be used is called its scope.

Global scope: the whole programx = 10 # globalLocal scope: only inside show()y = 5 # localprint(x + y) # can use both
A local variable lives only inside its function. A global variable can be read everywhere.

In daily life: The school rules apply to every class (global). A rule made by one class teacher applies only inside that classroom (local).

Exception handling

try:
    n = int(input("Number: "))
    print(100 / n)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Enter digits only")
else:
    print("No error")       # runs when try succeeds
finally:
    print("Always runs")    # runs in every case
ErrorWhen
ZeroDivisionErrordivide by 0
ValueErrorint("abc"), "abc".index("z")
TypeError5 + "5", tuple + list
IndexErrorindex outside list
KeyErrormissing dictionary key
NameErrorvariable not defined
EOFErrorpickle.load() at end of file
Remembertry-except catches run-time errors only. Syntax errors and logical errors (wrong answer, no crash) are not caught.

Picture: the path of try and except

Risky statements are kept in try. If an error comes, Python does not crash; it jumps to except.

try block runserror occurred ?Yesexcept block runsNoelse block runsfinally block: always runsrest of the program
finally runs in both cases, so it is the right place to close a file.

In daily life: A spare wheel in a car: you hope not to need it, but if a tyre fails you can still go on.

random module (Q25 type)

FunctionGives
random.random()float from 0.0 up to but not including 1.0
random.randint(a, b)integer from a to b, both included
random.randrange(a, b)integer from a to b-1, b not included

Method: write the smallest and largest value each variable can take, then strike off options that need a value outside that range.

math and statistics modules

CallResultMeaning
math.sqrt(16)4.0square root
math.ceil(4.2)5next whole number above
math.floor(4.8)4whole number below
math.pow(2, 3)8.0power, answer in float
math.fabs(-5)5.0positive value in float
statistics.mean([2, 4, 9])5average
statistics.median([2, 4, 9])4middle value
statistics.mode([1, 2, 2])2most frequent value

Module functions with examples

Write import math, import statistics or import random at the top of the program before using these.

math and statistics functions8 functions · 3 examples each
math.sqrt(x)square root; the answer is a float
>>> math.sqrt(16)
4.0

>>> math.sqrt(6.25)
2.5

>>> math.sqrt(2)
1.4142135623730951
math.ceil(x)the next whole number above x
>>> math.ceil(4.2)
5

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

>>> math.ceil(7)
7
math.floor(x)the whole number below x
>>> math.floor(4.8)
4

>>> math.floor(-4.2)
-5

>>> math.floor(7)
7
math.pow(x, y)x raised to y; the answer is a float
>>> math.pow(2, 3)
8.0

>>> math.pow(9, 0.5)
3.0

>>> math.pow(10, -1)
0.1
math.fabs(x)the positive value, as a float
>>> math.fabs(-5)
5.0

>>> math.fabs(3.2)
3.2

>>> math.fabs(0)
0.0
statistics.mean(L)the average
>>> statistics.mean([2, 4, 9])
5

>>> statistics.mean([1.5, 2.5])
2.0

>>> statistics.mean([10, 20, 30, 40])
25
statistics.median(L)the middle value after sorting
>>> statistics.median([2, 4, 9])
4

>>> statistics.median([4, 1, 3, 2])
2.5

>>> statistics.median([7])
7
statistics.mode(L)the value that comes most often
>>> statistics.mode([1, 2, 2])
2

>>> statistics.mode(["a", "b", "a"])
'a'

>>> statistics.mode([3, 3, 4, 4])
3
random functions3 functions · 3 examples each · results change on every run
random.random()a decimal number from 0.0 up to (not including) 1.0
>>> random.random()
any float such as 0.3741

>>> random.random() * 10
a float from 0.0 to less than 10.0

>>> int(random.random() * 6) + 1
1, 2, 3, 4, 5 or 6
random.randint(a, b)a whole number from a to b, BOTH included
>>> random.randint(1, 6)
1, 2, 3, 4, 5 or 6

>>> random.randint(10, 12)
10, 11 or 12

>>> random.randint(5, 5)
always 5
random.randrange(a, b)a whole number from a to b-1; b is NOT included
>>> random.randrange(1, 6)
1, 2, 3, 4 or 5

>>> random.randrange(0, 10, 5)
0 or 5

>>> random.randrange(3)
0, 1 or 2
4

File handling: three templates

Q29 text (3) + Q33 CSV (4) + Q36 binary (5) = 12 marks

A file is a named place on the disk where data is stored permanently. A variable loses its value when the program ends; a file keeps the data for later use.

1 Open the file→2 Read or write→3 Close the file

Absolute path

The full address starting from the drive.

C:\School\XII\notes.txt

Relative path

The address starting from the current folder.

notes.txt or data\notes.txt

File modes

ModeMeaningFile missing?Old data
r / rbread onlyErrorsafe
w / wbwrite onlycreateserased
a / abappend at endcreatessafe
r+ / rb+read and writeErrorsafe
w+ / wb+write and readcreateserased

Three kinds of file

  • Text (.txt): characters, read() readline() readlines() write()
  • Binary (.dat): Python objects, pickle.dump() writes, pickle.load() reads
  • CSV (.csv): comma separated rows, csv.writer and csv.reader

File pointer

  • f.tell() tells the current position in bytes.
  • f.seek(n) moves the pointer to byte n. f.seek(0) goes back to the start.
  • with open(...) as f: closes the file automatically.

Picture: why we need a file

Variables live in the memory (RAM). When the program ends or the computer is switched off, they are gone. A file keeps the data on the disk so that it can be used again.

Python program(in RAM, temporary)File on disk(permanent)write / dumpread / load
Data in the program is lost when the program ends. Data in a file stays on the disk.

In daily life: Writing homework in a notebook instead of only remembering it. The notebook is the file.

Picture: three kinds of files from inside

notes.txt
Hello class
Python is easy
Text file: plain characters. Anyone can read it.
marks.csv
RNo,Name,Marks
1,Asha,91
2,Ravi,78
CSV file: text in rows, values separated by commas. Opens in Excel.
data.dat
€♦•]q (K☺X♦ Asha K[ e.
Binary file: bytes written by pickle. Fast for Python, not readable by us.

Picture: the file pointer

The file pointer is like a finger on the page. It shows where the next reading or writing will happen.

File contents: Hello KV   1. Just after f = open("a.txt"): f.tell() is 0

0H
1e
2l
3l
4o
5
6K
7V

2. After f.read(5): five characters are read, f.tell() is 5

0H
1e
2l
3l
4o
5
6K
7V

3. After f.seek(0): the pointer is back at the start

0H
1e
2l
3l
4o
5
6K
7V

In daily life: A bookmark in a book: it remembers where you stopped, and you can move it to any page.

Picture: what each mode does to the file

"r" read
A
B
C
Old data stays. Pointer at the start. The file must exist.
"w" write
Old data is erased. You start with an empty file.
"a" append
A
B
C
Old data stays. Pointer at the end, new data is added there.

In daily life: Reading a notebook (r), taking a fresh notebook (w), and writing on the next empty line of the same notebook (a).

Reading and writing methods

MethodWhat it doesGives back
f.read()reads the whole fileone string
f.read(n)reads the next n charactersone string
f.readline()reads one line, including its \none string
f.readlines()reads all the linesa list of strings
f.write(s)writes the string s; add \n yourself for a new linenumber of characters written
f.writelines(L)writes all the strings of list L; no \n is addednothing

Picture: three ways of reading the same file

The file has three lines: Hello, World, Bye

f.read()
'Hello\nWorld\nBye\n'
everything, as one stringf.readline()
'Hello\n'
only one linef.readlines()
['Hello\n', 'World\n', 'Bye\n']
all lines, as a list

File functions with examples

In these examples the file a.txt has three lines: Hello, World, Bye.

Reading, writing and the file pointer6 functions · 3 examples each
f.read(n)reads n characters; the whole file when n is not given
>>> f = open("a.txt")
>>> f.read()
'Hello\nWorld\nBye\n'

>>> f = open("a.txt")
>>> f.read(5)
'Hello'

>>> f = open("a.txt")
>>> x = f.read(5)
>>> f.read(3)
'\nWo'
f.readline()reads one line, with its \n
>>> f = open("a.txt")
>>> f.readline()
'Hello\n'

>>> f = open("a.txt")
>>> x = f.readline()
>>> f.readline()
'World\n'

>>> f = open("a.txt")
>>> f.readline(3)
'Hel'
f.readlines()reads all the lines into a list
>>> f = open("a.txt")
>>> f.readlines()
['Hello\n', 'World\n', 'Bye\n']

>>> f = open("a.txt")
>>> len(f.readlines())
3

>>> f = open("a.txt")
>>> f.readlines()[1]
'World\n'
f.write(s)writes the string s; it does not add \n by itself
>>> f = open("b.txt", "w")
>>> f.write("Hi")
2

>>> f = open("b.txt", "w")
>>> x = f.write("Hi\n")
>>> x = f.write("KV")
>>> f.close()
>>> open("b.txt").read()
'Hi\nKV'

>>> f = open("a.txt", "a")
>>> x = f.write("End")
>>> f.close()
>>> open("a.txt").read()
'Hello\nWorld\nBye\nEnd'
f.writelines(L)writes every string of the list L; no \n is added
>>> f = open("b.txt", "w")
>>> f.writelines(["A\n", "B\n"])
>>> f.close()
>>> open("b.txt").read()
'A\nB\n'

>>> f = open("b.txt", "w")
>>> f.writelines(["A", "B"])
>>> f.close()
>>> open("b.txt").read()
'AB'

>>> f = open("b.txt", "w")
>>> f.writelines(("X\n", "Y"))
>>> f.close()
>>> open("b.txt").readlines()
['X\n', 'Y']
f.tell() and f.seek(n)tell() gives the pointer position; seek(n) moves the pointer to n
>>> f = open("a.txt")
>>> f.tell()
0

>>> f = open("a.txt")
>>> x = f.read(5)
>>> f.tell()
5

>>> f = open("a.txt")
>>> x = f.seek(6)
>>> f.read(5)
'World'

Text, binary and CSV files compared

PointText fileBinary fileCSV file
Storesreadable characters, lines end with EOLbytes, same as in memory; not readabletext rows, values separated by commas
Extension.txt.dat.csv
Modulenonepicklecsv
Readread() readline() readlines()pickle.load(f)csv.reader(f)
Writewrite() writelines()pickle.dump(obj, f)writerow() one row, writerows() many rows
Modesr, w, arb, wb, abr, w, a with newline=""
RememberPickling means changing a Python object (list, tuple, dictionary) into a stream of bytes; dump() does it. Unpickling is the reverse; load() does it.

Picture: pickling and unpickling

A binary file cannot store a list or dictionary directly. The pickle module first changes the object into bytes (pickling) and later changes the bytes back into the object (unpickling).

list / dictin the programfile .dat(bytes)list / dictback againdump()load()picklingunpickling

In daily life: Packing clothes into a suitcase for a journey (dump) and unpacking them at home (load).

Template 1 · Text file

# WORD based question
def count_word():
    f = open("Prog.txt", "r")
    words = f.read().split()
    c = 0
    for w in words:
        if w == "Python":      # change only this line
            c += 1
    print(c)
    f.close()
# LINE based question
def show_lines():
    f = open("Elections.txt", "r")
    for line in f:             # or f.readlines()
        if "vote" in line.lower().split():
            print(line, end="")
    f.close()

# CHARACTER based: for ch in f.read():
Asked to count or showCondition to write
digits in the fileif ch.isdigit():
vowels / capital lettersif ch in "aeiouAEIOU": / if ch.isupper():
words starting with a letterif w[0] in "Aa": or w.startswith("A")
words of length 4 or moreif len(w) >= 4:
lines starting with 'T'if line[0] == "T":
number of lineslen(f.readlines())

Template 2 · CSV file

import csv
def add_rec():
    f = open("stu.csv", "a", newline="")
    w = csv.writer(f)
    rno = int(input("Roll no: "))
    name = input("Name: ")
    marks = int(input("Marks: "))
    w.writerow([rno, name, marks])
    f.close()
import csv
def show_rec():
    f = open("stu.csv", "r")
    r = csv.reader(f)
    next(r)                    # skip header, only if file has one
    for row in r:
        if int(row[2]) > 75:   # CSV data comes as strings
            print(row)
    f.close()
Common mistakeEverything read from a CSV is a string. Convert with int() or float() before comparing or adding. Write newline="" while opening for writing.

Template 3 · Binary file

import pickle
def add_rec():
    f = open("emp.dat", "ab")
    eno = int(input("Emp no: "))
    name = input("Name: ")
    sal = float(input("Salary: "))
    pickle.dump([eno, name, sal], f)
    f.close()

def search(n):
    f = open("emp.dat", "rb")
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
    except EOFError:
        f.close()
import pickle
def update():
    f = open("emp.dat", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            rec[2] = rec[2] + 500      # the change
            data.append(rec)
    except EOFError:
        f.close()
    f = open("emp.dat", "wb")          # write all back
    for rec in data:
        pickle.dump(rec, f)
    f.close()
RememberBinary reading is always the same four lines: try → while True → pickle.load(f) → except EOFError. Learn this skeleton by heart.

Search, update and delete in a binary file

  • Search: load the records one by one and compare the required field.
  • Update: load every record into a list, change the required one, then write the whole list back in wb mode.
  • Delete: load every record, keep only the records you want in a list, then write that list back in wb mode.
5

Stack

Q30 · 3 marks every year

10 20 30 ◄ TOP PUSH POP Last In, First Out (LIFO)
30 went in last, so 30 comes out first. In Python the list end is the top.
stk = []

def push(stk, item):
    stk.append(item)            # PUSH = append

def pop(stk):
    if len(stk) == 0:           # empty check first
        print("Underflow")
    else:
        return stk.pop()        # POP = pop()

def peek(stk):
    if stk:
        return stk[-1]          # top, not removed

def display(stk):
    for i in range(len(stk)-1, -1, -1):
        print(stk[i])           # top to bottom

Picture: push and pop, step by step

stk = []
empty
push 10
10
top is 10
push 20
1020
top is 20
push 30
102030
top is 30
pop
1020
30 comes out
pop
10
20 comes out

The item that went in last (30) came out first. This is LIFO.

In daily life: A pile of plates in the canteen: you put a plate on the top and you take a plate from the top.

Try it Stack lab

A stack is a linear data structure in which items are added and removed at one end only, called the top. Think of a pile of plates: the plate kept last is taken first.

TermMeaning
Pushadd an item at the top
Popremove the item at the top
Peek / Topsee the top item without removing it
Underflowtrying to pop from an empty stack
Overflowtrying to push into a full stack

Where stacks are used

  • Undo in a text editor
  • Back button of a web browser
  • Reversing a string or a list
  • Keeping track of function calls
  • Checking matching brackets in an expression
RememberThe board changes only the push condition: "push if price > 250", "push three-digit even numbers", "push last 5 elements". The pop part with the empty check stays the same. Print the exact message the question gives ("Underflow", "Stack Empty").
6

Computer networks

Unit 2 · 10 marks, the easiest full score in the paper

A computer network is a group of two or more computers and devices connected together to share data and resources such as files, printers and the Internet.

How networking grew

ARPANET · 1969→NSFNET · 1980s→Internet

Data communication terms

TermMeaning
Senderthe device that sends the data
Receiverthe device that gets the data
Messagethe data being sent: text, picture, sound, video
Communication mediumthe path between sender and receiver: cable or wireless
Protocolthe set of rules both sides follow
Bandwidththe range of frequencies a channel can carry; measured in Hz, kHz, MHz
Data transfer rateamount of data sent in one second; measured in bps, Kbps, Mbps, Gbps
IP addressthe unique number of a device on a network, e.g. 192.168.1.10. IPv4 has 32 bits, IPv6 has 128 bits. It can change.
MAC addressthe 48-bit physical address fixed on the network card by the maker, e.g. 00:1A:2B:3C:4D:5E. It does not change.

Picture: the five parts of data communication

SenderMessageReceiverMedium: the cable or wireless path that carries the messageProtocol: the rules that both sides follow

In daily life: Sending a letter: you (sender), the letter (message), the postal van (medium), your friend (receiver), and the address format everyone follows (protocol).

Devices

DeviceOne-line job
ModemConverts digital to analog and back (modulation, demodulation)
RJ45Registered Jack 45, the connector on Ethernet cable
Ethernet card (NIC)Connects a computer to the network; carries a unique MAC address
Wi-Fi cardConnects a computer to a wireless network without a cable
RepeaterRegenerates a weak signal on long cable runs
HubSends data to all connected devices
SwitchSends data only to the destination device; use inside each building
RouterConnects different networks and chooses the path
GatewayEntry and exit point of a network; joins networks with different protocols

Picture: where each device sits

InternetModemRouterSwitchPCPCPCRepeaterlong cable toa far blockModem: joins the Internet lineRouter: joins two networksSwitch: joins the PCs of a blockRepeater: makes a weaksignal strong again
From the Internet to your PC: modem, then router, then switch.

Picture: hub and switch

HubPCPCPCsends to ALLSwitchPCPCPCsends to ONE
A hub repeats the data to every PC. A switch sends it only to the PC it is meant for.

In daily life: A hub is like an announcement on the school speaker: everyone hears it. A switch is like a phone call to one person.

Topologies

BUS SW STAR TREE
TopologyAdvantageDisadvantage
BusSimple, least cable, cheapBackbone cable fails, whole network stops; fault hard to find
StarOne cable fails, only that node stops; easy to add nodesCentral device fails, network stops; more cable
TreeHierarchical, easy to expand (bus + star)Backbone fails, the branches below it stop

Media and network types

Wired (guided)

  • Twisted pair: cheapest, short distance, inside buildings
  • Coaxial: cable TV, better shielding
  • Optical fibre: fastest, long distance, no electrical interference, costly

Wireless (unguided)

  • Radio waves: all directions, long distance, pass through walls, no line of sight needed (FM, hilly areas)
  • Microwaves: line of sight, towers
  • Infrared: very short range, TV remote

By area

  • PAN: around one person (Bluetooth)
  • LAN: one building or campus
  • MAN: one city
  • WAN: across cities and countries

Switching

  • Circuit: dedicated path is set up first (old telephone)
  • Packet: data broken into packets, each may take a different route (Internet)

Picture: networks by the area they cover

WAN: country or the whole world (the Internet)MAN: one cityLAN: one building or campusPAN: aroundone person

Picture: the three cables

Twisted paircheap, short distancetelephone, LANCoaxialbetter shieldingcable TVOptical fibrelight signals, fastestlong distance, costly

Picture: circuit switching and packet switching

Circuit switching: one fixed path is kept for the whole call132Packet switching: packets take different routes and join at the end

In daily life: Circuit switching is a train on its own reserved track. Packet switching is many courier parcels that travel by different roads and reach the same house.

Protocols and full forms

ShortFull formUse
HTTP / HTTPSHyperText Transfer Protocol (Secure)web pages
FTPFile Transfer Protocolupload and download files
SMTPSimple Mail Transfer Protocolsending e-mail
POP3Post Office Protocol version 3receiving e-mail
TCP/IPTransmission Control Protocol / Internet Protocolbase of the Internet
PPPPoint-to-Point Protocoldirect link between two devices
TELNETTeletype Networkremote login
VoIPVoice over Internet Protocolvoice and video calls over Internet
URLUniform Resource Locatoraddress of a web resource
XML / HTMLeXtensible / HyperText Markup LanguageXML carries data (own tags), HTML displays it (fixed tags)
ARPANETAdvanced Research Projects Agency Networkfirst network, ancestor of the Internet
MAC / NICMedia Access Control / Network Interface Cardphysical address / network card

Web services

TermMeaning
WWWWorld Wide Web: the collection of linked web pages opened through the Internet. It is one service of the Internet, not the Internet itself.
Web pageone document written in HTML
Websitea group of related web pages under one domain name
Web browsersoftware that opens web pages: Chrome, Firefox, Edge
Web serverthe computer or program that stores websites and sends pages to browsers
Web hostingthe service of keeping a website on a web server so that everyone can open it
Domain namethe easy name of a website that stands for its IP address: cbse.gov.in
URLthe complete address of one resource on the web

Parts of a URL

https://protocolwww.cbse.gov.indomain name/cbsenew/question-paper.htmlpath and file name

Picture: which protocol does which job

Open web pagesHTTP / HTTPS
Transfer filesFTP
Send e-mailSMTP
Receive e-mailPOP3
Remote loginTELNET
Voice and video callsVoIP
Direct link of two devicesPPP
Base of the InternetTCP/IP

In daily life: Different counters in a bank: one for cash, one for cheques, one for enquiry. Each protocol is a counter for one kind of work.

Picture: how a web page opens

You typethe URLWebbrowserDomain nameto IP addressWebserverthe server sends the web page back by HTTP / HTTPS
The domain name is changed into the IP address of the web server, and the server sends the page.

Q37 case study: six rules for five marks

  1. Server goes in the block with the most computers. Write that reason.
  2. Cable layout: draw a star from the server block to every other block.
  3. Switch or hub: one in every block.
  4. Repeater: on a cable run longer than about 100 m.
  5. Fastest wired medium: optical fibre. Hilly or far area without cable: radio waves or satellite.
  6. Video or voice meeting: VoIP. Remote login: TELNET. Offices in different cities: WAN. Inside the campus: LAN.
ACADEMIC 600 PCs · SERVER ADMIN25 PCs HOSTEL120 PCs SPORTS50 PCs 60 m40 m R 120 mrepeater here
CBSE 2026, Q37 worked out: ACADEMIC has the most computers so it gets the server; only the 120 m link needs a repeater.

Try it Case-study solver

Type the block names, number of computers and distances from any question. The data of CBSE 2026 is filled in.

7

Database and SQL

Unit 3 · 20 marks, almost all direct syntax

A database is an organised collection of related data. A DBMS (Database Management System) such as MySQL is the software used to create, store and use a database. In a relational database the data is kept in tables.

Why a database and not simple files?

  • Less repetition of data (redundancy)
  • No mismatch between copies (inconsistency)
  • Many users can share the data
  • Data is secure with passwords and rights
  • Searching is easy with queries
RNoNameMarks
1Asha91
2Ravi78
3Tina85
Relation STUDENT: 3 columns → degree 3; 3 rows → cardinality 3

Terms and keys

TermMeaning
Relationtable
Tuplerow / record
Attributecolumn / field
Degreenumber of columns
Cardinalitynumber of rows
Domainset of allowed values of a column

Keys in one picture

Candidate keys=Primary key+Alternate keys
  • Candidate: every column that can identify a row uniquely.
  • Primary: the one chosen. Unique and NOT NULL.
  • Alternate: candidates not chosen. 2 candidates → 1 alternate.
  • Foreign: a column that refers to the primary key of another table.
RememberDegree = Down columns, Cardinality = Count of rows. Adding a row changes cardinality only. ALTER TABLE changes degree. Cartesian product: rows multiply, columns add.

Picture: the parts of a table

RNoNameCityMarks
1AshaDelhi91
2RaviAgra78
3TinaDelhi85
blue row = one tuple (record)yellow column = one attribute (field)4 columns → degree 43 rows → cardinality 3values allowed in Marks, 0 to 100 → its domain

In daily life: The attendance register of a class: every student is one row, and every heading (Roll No, Name) is one column.

Picture: keys

STUDENTAdmNoprimary keyRollNoalternate keyNameFEEReceiptNoprimary keyAdmNoforeign keyAmountThe foreign key AdmNo in FEE points to theprimary key AdmNo in STUDENT
AdmNo and RollNo can both identify a student, so both are candidate keys.

In daily life: Your admission number is your primary key in school: no two students share it, and it is never blank.

Data types and constraints

Data typeStoresExample
INTwhole numbers25
FLOATnumbers with decimals91.5
DECIMAL(7,2)7 digits in all, 2 after the point99999.99
CHAR(n)text of fixed length n'XII'
VARCHAR(n)text of any length up to n'Asha'
DATEdate as 'YYYY-MM-DD''2027-03-15'
ConstraintRule it puts on a column
NOT NULLthe column cannot be left empty
UNIQUEno two rows can have the same value
PRIMARY KEYunique and not null; only one in a table

DDL and DML

DDL: changes structure

CREATE ALTER DROP

DML: changes or reads data

INSERT UPDATE DELETE SELECT

CREATE DATABASE school;
USE school;

CREATE TABLE student (
  rno   INT PRIMARY KEY,
  name  VARCHAR(20) NOT NULL,
  dob   DATE,
  marks FLOAT
);
SHOW TABLES;
DESC student;

ALTER TABLE student ADD city VARCHAR(15);
ALTER TABLE student MODIFY name VARCHAR(30);
ALTER TABLE student DROP COLUMN city;
DROP TABLE student;
INSERT INTO student VALUES (1,'Asha','2009-05-14',88.5);

UPDATE student SET marks = marks + 5 WHERE rno = 1;

DELETE FROM student WHERE marks < 33;

SELECT name, marks FROM student
WHERE marks BETWEEN 60 AND 90      -- both included
  AND rno IN (1, 2, 3)
  AND name LIKE 'A%'               -- % many, _ one char
  AND dob IS NOT NULL
ORDER BY marks DESC;

SELECT DISTINCT name FROM student;

Picture: two families of SQL commands

DDL: works on the structure

CREATEALTERDROP

Makes, changes or removes the table itself.

DML: works on the data

INSERTUPDATEDELETESELECT

Adds, changes, removes or shows the rows.

In daily life: DDL is building the almirah and its shelves. DML is keeping clothes in it, changing them, taking them out, or just looking at them.

Grouping and the order of clauses

SELECT→FROM→WHERE→GROUP BY→HAVING→ORDER BY
SELECT city, COUNT(*), AVG(marks)
FROM student
GROUP BY city
HAVING COUNT(*) > 5;

-- Aggregate functions
-- SUM() AVG() MAX() MIN() COUNT()
-- Equi join: common column in WHERE
SELECT s.name, f.amount
FROM student s, fee f
WHERE s.rno = f.rno AND f.amount > 5000;

-- Natural join: common column shown once
SELECT * FROM student NATURAL JOIN fee;

-- Cartesian product: no condition
SELECT * FROM student, fee;

Picture: how one SELECT query works, step by step

SELECT city, COUNT(*) FROM student
WHERE marks > 60
GROUP BY city
HAVING COUNT(*) > 1;
1
FROM student

Take the whole table.

namecitymarks
AshaDelhi91
RaviAgra55
TinaDelhi78
OmAgra82
ZoyaPune67
2
WHERE marks > 60

Keep only the rows that pass the condition. Ravi (55) goes out.

namecitymarks
AshaDelhi91
TinaDelhi78
OmAgra82
ZoyaPune67
3
GROUP BY city

Put the rows of the same city together.

cityrows in the group
DelhiAsha, Tina
AgraOm
PuneZoya
4
HAVING COUNT(*) > 1

Keep only the groups that pass the condition.

cityrows in the group
DelhiAsha, Tina
5
SELECT city, COUNT(*)

Show the asked columns. This is the output.

cityCOUNT(*)
Delhi2

In daily life: Sorting answer sheets: take all sheets, remove the absent ones (WHERE), make bundles class-wise (GROUP BY), keep only the big bundles (HAVING), and write the count of each bundle.

Pattern matching, NULL and alias

LIKE patternMatches
'A%'starts with A
'%a'ends with a
'%an%'contains "an" anywhere
'_a%'second letter is a
'____'exactly four characters

NULL and alias

  • NULL means the value is missing or not known. It is not zero and not a space.
  • Aggregate functions skip NULL values.
  • An alias is a temporary heading for a column: SELECT name AS Student, marks*2 AS Double_Marks FROM student;

Try it LIKE pattern tester

% stands for any number of characters, _ stands for exactly one character. MySQL ignores capital and small letters while matching.

Joins with a small example

STUDENTFEE
rnonamernoamount
1Asha15000
2Ravi24500
JoinRowsColumns
Cartesian product: every row with every row2 x 2 = 42 + 2 = 4
Equi join: only rows where rno matches24 (rno twice)
Natural join: matching rows, common column once23

Picture: which rows a join keeps

STUDENT (rno, name)FEE (rno, amount)1 Asha2 Ravi3 Tina1 50002 4500matchmatchno fee row for 3Join output: 2 rows. Cartesian product: 3 x 2 = 6 rows.
Only the rows whose rno matches in both tables come in an equi join or natural join.

In daily life: Matching the fee receipts with the class list: a receipt is joined to the student who has the same roll number.

SQL functions and clauses with examples

Each example shows the query and the output it gives on the table below. Every example starts again from this same table.

Table: student (used in all the examples below)

rnonamecitymarksfee
1AshaDelhi915000
2RaviAgra554500
3TinaDelhi78NULL
4OmAgra825000
5ZoyaPune674000
Aggregate functions5 commands · 3 examples each
SUM(column)adds the values of a column; NULL is skipped
SELECT SUM(marks) FROM student;
SUM(marks)
373
SELECT SUM(fee) FROM student;
SUM(fee)
18500
SELECT SUM(marks) FROM student WHERE city = 'Delhi';
SUM(marks)
169
AVG(column)the average of a column; NULL is skipped
SELECT AVG(marks) FROM student;
AVG(marks)
74.6
SELECT AVG(fee) FROM student;
AVG(fee)
4625.0
SELECT AVG(marks) FROM student WHERE city = 'Agra';
AVG(marks)
68.5
MAX(column)the largest value
SELECT MAX(marks) FROM student;
MAX(marks)
91
SELECT MAX(name) FROM student;
MAX(name)
Zoya
SELECT city, MAX(marks)
  FROM student GROUP BY city;
cityMAX(marks)
Agra82
Delhi91
Pune67
MIN(column)the smallest value
SELECT MIN(marks) FROM student;
MIN(marks)
55
SELECT MIN(fee) FROM student;
MIN(fee)
4000
SELECT MIN(marks) FROM student WHERE city = 'Delhi';
MIN(marks)
78
COUNT()COUNT(*) counts rows; COUNT(column) skips NULL
SELECT COUNT(*) FROM student;
COUNT(*)
5
SELECT COUNT(fee) FROM student;
COUNT(fee)
4
SELECT COUNT(DISTINCT city) FROM student;
COUNT(DISTINCT city)
3
Clauses and operators of SELECT9 commands · 3 examples each
WHEREkeeps only the rows that pass the condition
SELECT name, marks FROM student WHERE marks > 80;
namemarks
Asha91
Om82
SELECT name FROM student WHERE city = 'Delhi';
name
Asha
Tina
SELECT name FROM student WHERE marks >= 60 AND city <> 'Delhi';
name
Om
Zoya
DISTINCTshows each value only once
SELECT DISTINCT city FROM student;
city
Delhi
Agra
Pune
SELECT DISTINCT fee FROM student WHERE fee IS NOT NULL;
fee
5000
4500
4000
SELECT COUNT(DISTINCT fee) FROM student;
COUNT(DISTINCT fee)
3
BETWEEN a AND bvalues from a to b, both included
SELECT name, marks FROM student WHERE marks BETWEEN 60 AND 80;
namemarks
Tina78
Zoya67
SELECT name FROM student WHERE fee BETWEEN 4000 AND 4500;
name
Ravi
Zoya
SELECT name FROM student WHERE marks NOT BETWEEN 60 AND 90;
name
Asha
Ravi
IN (list)matches any one value of the list
SELECT name FROM student WHERE city IN ('Delhi', 'Pune');
name
Asha
Tina
Zoya
SELECT name FROM student WHERE marks IN (55, 67);
name
Ravi
Zoya
SELECT name FROM student WHERE city NOT IN ('Delhi', 'Agra');
name
Zoya
LIKE pattern% means any number of characters, _ means exactly one
SELECT name FROM student WHERE name LIKE 'A%';
name
Asha
SELECT name FROM student WHERE name LIKE '%a';
name
Asha
Tina
Zoya
SELECT name FROM student WHERE name LIKE '_o%';
name
Zoya
IS NULLfinds the rows where a value is missing
SELECT name FROM student WHERE fee IS NULL;
name
Tina
SELECT name FROM student WHERE fee IS NOT NULL;
name
Asha
Ravi
Om
Zoya
SELECT COUNT(*) FROM student WHERE fee IS NULL;
COUNT(*)
1
ORDER BYsorts the output; ascending unless DESC is written
SELECT name, marks FROM student ORDER BY marks;
namemarks
Ravi55
Zoya67
Tina78
Om82
Asha91
SELECT name, marks FROM student ORDER BY marks DESC;
namemarks
Asha91
Om82
Tina78
Zoya67
Ravi55
SELECT city, name FROM student ORDER BY city, name;
cityname
AgraOm
AgraRavi
DelhiAsha
DelhiTina
PuneZoya
GROUP BYmakes one group for every different value
SELECT city, COUNT(*)
  FROM student GROUP BY city;
cityCOUNT(*)
Agra2
Delhi2
Pune1
SELECT city, MAX(marks)
  FROM student GROUP BY city;
cityMAX(marks)
Agra82
Delhi91
Pune67
SELECT city, SUM(fee)
  FROM student GROUP BY city;
citySUM(fee)
Agra9500
Delhi5000
Pune4000
HAVINGkeeps only the groups that pass the condition
SELECT city, COUNT(*)
  FROM student
  GROUP BY city HAVING COUNT(*) > 1;
cityCOUNT(*)
Agra2
Delhi2
SELECT city, AVG(marks)
  FROM student
  GROUP BY city HAVING AVG(marks) > 70;
cityAVG(marks)
Delhi84.5
SELECT city, MAX(marks)
  FROM student
  GROUP BY city HAVING MAX(marks) < 80;
cityMAX(marks)
Pune67
Changing the data: INSERT, UPDATE, DELETE3 commands · 3 examples each
INSERT INTOadds a new row
INSERT INTO student VALUES (6, 'Neha', 'Pune', 88, 4000);

1 row changed.

INSERT INTO student (rno, name) VALUES (7, 'Dev');

1 row changed.

INSERT INTO student VALUES (8, 'Kabir', 'Agra', 74, NULL);

1 row changed.

UPDATE ... SETchanges values in the rows that pass the condition
UPDATE student SET marks = 60 WHERE rno = 2;

1 row changed.

UPDATE student SET fee = fee + 500 WHERE city = 'Delhi';

2 rows changed.

UPDATE student SET city = 'Noida', fee = 4200 WHERE name = 'Zoya';

1 row changed.

DELETE FROMremoves the rows that pass the condition; the table stays
DELETE FROM student WHERE rno = 5;

1 row changed.

DELETE FROM student WHERE marks < 60;

1 row changed.

DELETE FROM student WHERE fee IS NULL;

1 row changed.

Changing the structure: CREATE, ALTER, DROP3 commands · 3 examples each
CREATE TABLEmakes a new table
CREATE TABLE student (rno INT PRIMARY KEY,
  name VARCHAR(20) NOT NULL,
  city VARCHAR(15), marks INT, fee INT);

A new empty table is created with these columns.

CREATE TABLE book (bno INT PRIMARY KEY, title VARCHAR(30), price FLOAT);

A new empty table is created with these columns.

CREATE TABLE member (mno INT, mname VARCHAR(25) NOT NULL, phone CHAR(10) UNIQUE, doj DATE);

A new empty table is created with these columns.

ALTER TABLEchanges the structure of a table
ALTER TABLE student ADD email VARCHAR(30);

A new column email is added. Old rows have NULL in it.

ALTER TABLE student MODIFY name VARCHAR(40);

The column name can now hold 40 characters.

ALTER TABLE student DROP COLUMN fee;

The column fee is removed. The degree becomes 4.

DROPremoves a table or a database completely
DROP TABLE student;

The table student and all its rows are gone.

DROP TABLE book;

The table book is removed.

DROP DATABASE school;

The whole database school, with all its tables, is removed.

Differences asked for 2 marks

PairFirstSecond
ALTER / UPDATEDDL, changes table structureDML, changes data in rows
DELETE / DROPremoves rows, table staysremoves the whole table
WHERE / HAVINGcondition on rows, before groupingcondition on groups, used with GROUP BY
CHAR / VARCHARfixed lengthvariable length
PRIMARY KEY / UNIQUEone per table, no NULLmany per table, NULL allowed
COUNT(*) / COUNT(col)counts all rowsskips NULL in that column
Common mistakeWrite IS NULL, never = NULL. Put text and dates in quotes: '2024-12-31'. End every query with a semicolon.

Python-MySQL connectivity (Q35 · 4 marks)

Picture: Python and MySQL talking to each other

Pythonprogrammysql.connector(the bridge)MySQLdatabasethe query goes this waythe rows come back this way

In daily life: Ordering food by phone: you call (connect), tell the order (execute), confirm it (commit), receive the food (fetch), and hang up (close).

  1. import mysql.connector
  2. connect(host, user, password, database)
  3. cursor()
  4. execute("query")
  5. commit() for INSERT, UPDATE, DELETE · fetchall() for SELECT
  6. close()
import mysql.connector
con = mysql.connector.connect(host="localhost",
        user="root", password="tiger", database="school")
cur = con.cursor()

# SELECT
cur.execute("SELECT * FROM student WHERE marks > 75")
for row in cur.fetchall():
    print(row)

# INSERT with user input
r = int(input("Roll: ")); n = input("Name: ")
cur.execute("INSERT INTO student(rno,name) VALUES(%s,%s)", (r, n))
con.commit()            # without this, nothing is saved
con.close()

fetchone() gives one row, fetchmany(n) gives n rows, fetchall() gives all rows as a list of tuples, cur.rowcount gives the number of rows affected.

8

Question bank: every type, 40 or more solved

1131 questions in 20 types, arranged in the order of the CBSE Sample Paper 2026-27

SQP 2026-27 44 items from the CBSE sample paper (OR-parts counted separately) CBSE 2026 34 from the 2026 board paper CBSE 2025 37 from the 2025 board paper Practice 1016 written on the same pattern

Tap a type to open it. In Section A, tap an option or type the output to check yourself. Board and sample-paper questions are shortened and reworded; open the official papers (links at the end) for the exact wording, tables and figures.

Section A · 1 mark each

A1Python MCQ and True/False1 mark · 124 questions
A1.1SQP 2026-271 mark

Which of the following data types in Python is mutable?

Answer

(d) List A list can be changed in place. The other three cannot.

A1.2SQP 2026-271 mark

t = (1, 2, 3) and l = [4, 5]. What happens on print(t + l)?

Answer

(c) Error, because a tuple cannot be joined with a list + needs both operands of the same sequence type, so TypeError is raised.

A1.3SQP 2026-271 mark

Dl is a dictionary with keys 'Pen', 'Pencil', 'Scale', 'InkPen' and number values. print(12 in Dl) shows ...

Answer

(a) False in checks the keys of a dictionary, not the values.

A1.4SQP 2026-271 mark

What is the data type of the result of 5 // 2?

Answer

(b) int Floor division of two integers gives an integer (2).

A1.5SQP 2026-271 mark

A global y = 8 exists. Inside update() the statement y = y + 2 is written without global y, and then y is printed. The output is ...

Answer

(c) Error Assigning to y makes it local, and it is read before it has a value: UnboundLocalError.

A1.6SQP 2026-271 mark

data(num) returns 190 / (29 - num). On ZeroDivisionError it writes "Num was 29" to errorlog.txt. What is in the file after data(29)?

Answer

(a) Num was 29 29 - 29 is 0, so the except block runs and writes the message.

A1.7CBSE 20261 mark

State True or False: In Python, the data type of 74 is the same as the data type of 74.0.

Answer

(b) False 74 is int and 74.0 is float.

A1.8CBSE 20261 mark

Which of the following statements is true about dictionaries in Python?

Answer

(b) A dictionary cannot have two elements with the same key Keys must be unique. Values can repeat.

A1.9CBSE 20261 mark

State True or False: Logical errors can be handled with try-except-finally.

Answer

(b) False Only run-time errors (exceptions) can be handled.

A1.10CBSE 20261 mark

Which file mode opens a binary .dat file only for reading?

Answer

(b) rb r = read, b = binary.

A1.11CBSE 20251 mark

State True or False: A Python list must always contain all its elements of the same data type.

Answer

(b) False A list can mix types: [1, 'a', 2.5].

A1.12CBSE 20251 mark

Which of the following is a valid identifier and not a keyword?

Answer

(b) Break Python is case-sensitive; only break is a keyword.

A1.13CBSE 20251 mark

Which operator checks whether two names refer to the same object?

Answer

(a) is is compares identity; == compares values.

A1.14CBSE 20251 mark

Which of the following print() calls is invalid?

Answer

(b) print("A", sep="*", 10) A positional argument (10) cannot come after a keyword argument (sep).

A1.15Practice1 mark

Which of the following is not a Python keyword?

Answer

(b) eval eval is a built-in function, not a keyword.

A1.16Practice1 mark

Which of the following is an invalid identifier?

Answer

(c) 1total An identifier cannot start with a digit.

A1.17Practice1 mark

The input() function always returns a value of type ...

Answer

(b) str Use int() or float() to convert the string.

A1.18Practice1 mark

Which of these operators has the highest precedence?

Answer

(c) ** Power is evaluated before multiplication and addition.

A1.19Practice1 mark

Which statement skips the rest of the current round of a loop and starts the next round?

Answer

(b) continue break leaves the loop; continue goes to the next round.

A1.20Practice1 mark

range(1, 10, 3) generates the numbers ...

Answer

(a) 1, 4, 7 Start 1, step 3, and the stop value 10 is not included.

A1.21Practice1 mark

A Python string is ...

Answer

(b) an immutable sequence Characters are indexed, but they cannot be changed in place.

A1.22Practice1 mark

Which of the following creates a tuple with one element?

Answer

(b) (5,) The comma makes it a tuple; (5) is just the integer 5.

A1.23Practice1 mark

Which list method adds one element at the end of a list?

Answer

(b) append() extend() adds many elements; insert() needs a position.

A1.24Practice1 mark

Which list method removes and returns the last element?

Answer

(b) pop() pop() without an index removes the last element.

A1.25Practice1 mark

The keys of a dictionary must be ...

Answer

(b) immutable int, float, str and tuple can be keys; a list cannot.

A1.26Practice1 mark

D.get(k) returns ______ when the key k is not in the dictionary.

Answer

(b) None D[k] would raise KeyError; get() does not.

A1.27Practice1 mark

Which keyword is used to define a function?

Answer

(b) def A function starts with def, e.g. def area(r):

A1.28Practice1 mark

A function that has no return statement returns ...

Answer

(b) None Without return, a function gives back None.

A1.29Practice1 mark

For def f(a, b=5, c=10): which call is invalid?

Answer

(c) f() a has no default value, so one argument is compulsory.

A1.30Practice1 mark

A variable created inside a function is called a ______ variable.

Answer

(b) local It exists only inside that function, so it is a local variable.

A1.31Practice1 mark

Which keyword lets a function change a global variable?

Answer

(a) global Writing global x inside the function makes assignments change the global x instead of creating a local one.

A1.32Practice1 mark

The values passed to a function in the function call are called ...

Answer

(b) arguments Parameters are the names in the function header.

A1.33Practice1 mark

Which block of exception handling always runs?

Answer

(d) finally finally runs whether or not an exception occurred, so it is used for clean-up such as closing files.

A1.34Practice1 mark

int("abc") raises ...

Answer

(b) ValueError The type is right (a string) but the value cannot be converted.

A1.35Practice1 mark

Reading L[10] from a list of 3 elements raises ...

Answer

(b) IndexError Valid indexes are 0 to 2 (or -1 to -3), so index 10 raises IndexError.

A1.36Practice1 mark

Using a variable that was never defined raises ...

Answer

(a) NameError Python cannot find the name, so NameError is raised.

A1.37Practice1 mark

Which method reads the whole text file as one string?

Answer

(a) read() read() returns all the text as one string; readline() gives one line and readlines() a list of lines.

A1.38Practice1 mark

readlines() returns ...

Answer

(b) a list of strings Each element is one line of the file.

A1.39Practice1 mark

Which mode opens a text file to add data at the end?

Answer

(c) a a = append.

A1.40Practice1 mark

Which module is used to read and write binary files of Python objects?

Answer

(b) pickle pickle.dump() writes an object to a binary file and pickle.load() reads it back.

A1.41Practice1 mark

pickle.load() raises ______ when no record is left in the file.

Answer

(a) EOFError EOF means End Of File.

A1.42Practice1 mark

Which method of a csv writer object writes one row?

Answer

(b) writerow() writerows() writes many rows.

A1.43Practice1 mark

f.seek(0) ...

Answer

(b) moves the file pointer to the beginning tell() returns the position.

A1.44Practice1 mark

A stack follows the ______ principle.

Answer

(b) LIFO Last In, First Out.

A1.45Practice1 mark

How many times will the body of the loop for i in range(0, 10, 2): run?

Answer

(d) 5 The values of i are 0, 2, 4, 6, 8.

A1.46Practice1 mark

How many times will the body of the loop for i in range(1, 10, 3): run?

Answer

(d) 3 The values of i are 1, 4, 7.

A1.47Practice1 mark

How many times will the body of the loop for i in range(5, 0, -1): run?

Answer

(b) 5 The values of i are 5, 4, 3, 2, 1.

A1.48Practice1 mark

How many times will the body of the loop for i in range(2, 20, 4): run?

Answer

(c) 5 The values of i are 2, 6, 10, 14, 18.

A1.49Practice1 mark

How many times will the body of the loop for i in range(10, 1, -3): run?

Answer

(a) 3 The values of i are 10, 7, 4.

A1.50Practice1 mark

How many times will the body of the loop for i in range(0, 7, 1): run?

Answer

(d) 7 The values of i are 0, 1, 2, 3, 4, 5, 6.

A1.51Practice1 mark

How many times will the body of the loop for i in range(3, 3, 1): run?

Answer

(b) 0 The start is not less than the stop, so the loop does not run.

A1.52Practice1 mark

How many times will the body of the loop for i in range(1, 16, 5): run?

Answer

(d) 3 The values of i are 1, 6, 11.

A1.53Practice1 mark

How many times will the body of the loop for i in range(20, 10, -2): run?

Answer

(c) 5 The values of i are 20, 18, 16, 14, 12.

A1.54Practice1 mark

How many times will the body of the loop for i in range(4, 25, 7): run?

Answer

(d) 3 The values of i are 4, 11, 18.

A1.55Practice1 mark

How many times will the body of the loop for i in range(0, 9, 4): run?

Answer

(d) 3 The values of i are 0, 4, 8.

A1.56Practice1 mark

How many times will the body of the loop for i in range(6, 0, -2): run?

Answer

(b) 3 The values of i are 6, 4, 2.

A1.57Practice1 mark

What is the data type of the value of 7 / 2?

Answer

(d) float The value is 3.5.

A1.58Practice1 mark

What is the data type of the value of "7" * 2?

Answer

(b) str The value is '77'.

A1.59Practice1 mark

What is the data type of the value of [1] + [2]?

Answer

(d) list The value is [1, 2].

A1.60Practice1 mark

What is the data type of the value of (1, 2) + (3,)?

Answer

(b) tuple The value is (1, 2, 3).

A1.61Practice1 mark

What is the data type of the value of 3 > 2?

Answer

(b) bool The value is True.

A1.62Practice1 mark

What is the data type of the value of {"a": 1}?

Answer

(b) dict The value is {'a': 1}.

A1.63Practice1 mark

What is the data type of the value of int("5") + 2.0?

Answer

(a) float The value is 7.0.

A1.64Practice1 mark

What is the data type of the value of "5" + "5"?

Answer

(c) str The value is '55'.

A1.65Practice1 mark

What is the data type of the value of len("abc")?

Answer

(c) int The value is 3.

A1.66Practice1 mark

What is the data type of the value of [1, 2][0:1]?

Answer

(d) list The value is [1].

A1.67Practice1 mark

What is the data type of the value of "abc"[0]?

Answer

(c) str The value is 'a'.

A1.68Practice1 mark

What is the data type of the value of 10 // 3?

Answer

(d) int The value is 3.

A1.69Practice1 mark

What is the value of the expression 7 + 3 * 2?

Answer

(c) 13 Precedence: ** first, then * / // % (left to right), then + -. Working: 3 * 2 = 6; 7 + 6 = 13.

A1.70Practice1 mark

What is the value of the expression (7 + 3) * 2?

Answer

(b) 20 Precedence: ** first, then * / // % (left to right), then + -. Working: 7 + 3 = 10; 10 * 2 = 20.

A1.71Practice1 mark

What is the value of the expression 2 ** 3 + 1?

Answer

(b) 9 Precedence: ** first, then * / // % (left to right), then + -. Working: 2 ** 3 = 8; 8 + 1 = 9.

A1.72Practice1 mark

What is the value of the expression 17 % 5 * 2?

Answer

(a) 4 Precedence: ** first, then * / // % (left to right), then + -. Working: 17 % 5 = 2; 2 * 2 = 4.

A1.73Practice1 mark

What is the value of the expression 9 // 2 + 9 % 2?

Answer

(b) 5 Precedence: ** first, then * / // % (left to right), then + -. Working: 9 // 2 = 4; 9 % 2 = 1; 4 + 1 = 5.

A1.74Practice1 mark

What is the value of the expression 10 - 4 // 2?

Answer

(d) 8 Precedence: ** first, then * / // % (left to right), then + -. Working: 4 // 2 = 2; 10 - 2 = 8.

A1.75Practice1 mark

What is the value of the expression 2 * 3 ** 2?

Answer

(b) 18 Precedence: ** first, then * / // % (left to right), then + -. Working: 3 ** 2 = 9; 2 * 9 = 18.

A1.76Practice1 mark

What is the value of the expression 15 // 4 * 4?

Answer

(a) 12 Precedence: ** first, then * / // % (left to right), then + -. Working: 15 // 4 = 3; 3 * 4 = 12.

A1.77Practice1 mark

What is the value of the expression len("CBSE") * 3?

Answer

(d) 12 Precedence: ** first, then * / // % (left to right), then + -. Working: len('CBSE') = 4; 4 * 3 = 12.

A1.78Practice1 mark

What is the value of the expression 20 - 3 * 4 + 2?

Answer

(b) 10 Precedence: ** first, then * / // % (left to right), then + -. Working: 3 * 4 = 12; 20 - 12 = 8; 8 + 2 = 10.

A1.79Practice1 mark

What is the value of the expression 8 % 3 ** 2?

Answer

(d) 8 Precedence: ** first, then * / // % (left to right), then + -. Working: 3 ** 2 = 9; 8 % 9 = 8.

A1.80Practice1 mark

What is the value of the expression 6 + 18 // 4?

Answer

(d) 10 Precedence: ** first, then * / // % (left to right), then + -. Working: 18 // 4 = 4; 6 + 4 = 10.

A1.81Practice1 mark

What is the value of the expression 5 * 2 ** 2 - 1?

Answer

(d) 19 Precedence: ** first, then * / // % (left to right), then + -. Working: 2 ** 2 = 4; 5 * 4 = 20; 20 - 1 = 19.

A1.82Practice1 mark

What is the value of the expression 100 // 7 % 4?

Answer

(c) 2 Precedence: ** first, then * / // % (left to right), then + -. Working: 100 // 7 = 14; 14 % 4 = 2.

A1.83Practice1 mark

Which error does the statement "abc" + 5 raise?

Answer

(c) TypeError A str and an int cannot be added with +, so TypeError.

A1.84Practice1 mark

Which error does the statement [1, 2, 3][5] raise?

Answer

(a) IndexError Index 5 does not exist in a list of 3 elements: IndexError.

A1.85Practice1 mark

Which error does the statement {"a": 1}["b"] raise?

Answer

(d) KeyError The key "b" is not in the dictionary: KeyError.

A1.86Practice1 mark

Which error does the statement int("x1") raise?

Answer

(c) ValueError "x1" is a string but not a valid number, so int() raises ValueError.

A1.87Practice1 mark

Which error does the statement print(xyz) raise? (xyz was never given a value.)

Answer

(c) NameError xyz has no value, so Python cannot find the name: NameError.

A1.88Practice1 mark

Which error does the statement 5 % 0 raise?

Answer

(d) ZeroDivisionError Taking a remainder by 0 is not possible: ZeroDivisionError.

A1.89Practice1 mark

Which error does the statement (1, 2)[3] raise?

Answer

(c) IndexError The tuple has indexes 0 and 1 only: IndexError.

A1.90Practice1 mark

Which error does the statement float("ten") raise?

Answer

(a) ValueError "ten" is not written in digits, so float() raises ValueError.

A1.91Practice1 mark

Which error does the statement [1, 2].remove(5) raise?

Answer

(a) ValueError remove() raises ValueError when the value is not in the list.

A1.92Practice1 mark

Which error does the statement len(5) raise?

Answer

(b) TypeError An int has no length, so len() raises TypeError.

A1.93Practice1 mark

A function is defined as def f(a, b=3): return a * b. What is the value of f(4)?

Answer

(c) 12 b takes its default value 3.

A1.94Practice1 mark

A function is defined as def f(a, b=3): return a * b. What is the value of f(4, 2)?

Answer

(b) 8 b takes the second value passed.

A1.95Practice1 mark

A function is defined as def f(a, b=10): return a + b. What is the value of f(5)?

Answer

(a) 15 b takes its default value 10.

A1.96Practice1 mark

A function is defined as def f(a, b=10): return a + b. What is the value of f(5, 1)?

Answer

(b) 6 b takes the second value passed.

A1.97Practice1 mark

A function is defined as def f(a, b=2): return a ** b. What is the value of f(3)?

Answer

(d) 9 b takes its default value 2.

A1.98Practice1 mark

A function is defined as def f(a, b=2): return a ** b. What is the value of f(2, 5)?

Answer

(b) 32 b takes the second value passed.

A1.99Practice1 mark

A function is defined as def f(a, b=4): return a - b. What is the value of f(9)?

Answer

(b) 5 b takes its default value 4.

A1.100Practice1 mark

A function is defined as def f(a, b=4): return a - b. What is the value of f(9, 9)?

Answer

(b) 0 b takes the second value passed.

A1.101Practice1 mark

A function is defined as def f(a, b=5): return a // b. What is the value of f(17)?

Answer

(d) 3 b takes its default value 5.

A1.102Practice1 mark

A function is defined as def f(a, b=5): return a // b. What is the value of f(17, 2)?

Answer

(c) 8 b takes the second value passed.

A1.103Practice1 mark

A function is defined as def f(a, b=3): return a % b. What is the value of f(10)?

Answer

(c) 1 b takes its default value 3.

A1.104Practice1 mark

A function is defined as def f(a, b=3): return a % b. What is the value of f(10, 4)?

Answer

(d) 2 b takes the second value passed.

A1.105Practice1 mark

What is the output of print("hello World".upper())?

Answer

(a) HELLO WORLD upper() changes every letter to capital.

A1.106Practice1 mark

What is the output of print("hello World".title())?

Answer

(b) Hello World title() makes the first letter of every word capital and the others small.

A1.107Practice1 mark

What is the output of print("pYTHON lab".capitalize())?

Answer

(d) Python lab capitalize() makes only the first character capital and all the other letters small.

A1.108Practice1 mark

What is the output of print("pYTHON lab".lower())?

Answer

(d) python lab lower() changes every letter to small.

A1.109Practice1 mark

What is the output of print("cbse BOARD exam".title())?

Answer

(c) Cbse Board Exam title() makes the first letter of every word capital.

A1.110Practice1 mark

What is the output of print("cbse BOARD exam".upper())?

Answer

(b) CBSE BOARD EXAM upper() changes every letter to capital.

A1.111Practice1 mark

What is the output of print("kV delhi".capitalize())?

Answer

(c) Kv delhi capitalize() makes only the first character of the whole string capital.

A1.112Practice1 mark

What is the output of print("kV delhi".title())?

Answer

(d) Kv Delhi title() makes the first letter of every word capital.

A1.113Practice1 mark

What is the output of print("gOOD luck".lower())?

Answer

(a) good luck lower() changes every letter to small.

A1.114Practice1 mark

What is the output of print("gOOD luck".capitalize())?

Answer

(d) Good luck capitalize() gives a capital first letter and makes all the other letters small.

A1.115Practice1 mark

Which statement opens "data.csv" so that new rows are added without erasing the old rows?

Answer

(a) open("data.csv", "a") a = append.

A1.116Practice1 mark

Which method of a csv writer object writes many rows in one call?

Answer

(b) writerows() writerow() writes one row; writerows() takes a list of rows and writes them all.

A1.117Practice1 mark

f = open("a.txt") opens the file in which mode?

Answer

(a) r Read mode is the default.

A1.118Practice1 mark

Which mode allows both reading and writing and does not erase the existing data?

Answer

(b) r+ r+ opens an existing file for reading and writing without erasing it; w+ would erase it.

A1.119Practice1 mark

A stack is stored in the list st. Which expression gives the top element without removing it?

Answer

(b) st[-1] The top of the stack is the last element, st[-1]; st.pop() would remove it.

A1.120Practice1 mark

Which operation is not allowed on a stack?

Answer

(c) Insert in the middle A stack works at one end only.

A1.121Practice1 mark

To write objects with pickle.dump(), the file should be opened in mode ...

Answer

(c) wb pickle writes bytes, so the file must be opened in binary write mode 'wb' (or 'ab').

A1.122Practice1 mark

How many values can a Python function return?

Answer

(c) One or more Many values are returned as a tuple.

A1.123Practice1 mark

What is the advantage of with open("a.txt") as f:?

Answer

(b) The file is closed automatically The with block closes the file automatically, even if an error occurs.

A1.124Practice1 mark

Which statement imports only the function sqrt from the math module?

Answer

(b) from math import sqrt from math import sqrt brings in only sqrt, which can then be used without writing math.

A2Output of a statement1 mark · 106 questions
A2.1SQP 2026-271 mark

Write the output.

L1 = [10, 20, 25, 30]
L1.insert(1, 15)
print(L1)
Answer
[10, 15, 20, 25, 30]

Working (step by step)

LineStatementValues after this stepPrinted
1L1 = [10, 20, 25, 30]L1 = [10, 20, 25, 30]
2L1.insert(1, 15)L1 = [10, 15, 20, 25, 30]
3print(L1)[10, 15, 20, 25, 30]⏎
A2.2SQP 2026-271 mark

Write the output.

print("programming is amazing".split("m"))
Answer
['progra', '', 'ing is a', 'azing']

Working (step by step)

LineStatementValues after this stepPrinted
1print("programming is amazing".split("m"))['progra', '', 'ing is a', 'azing']⏎
A2.3SQP 2026-271 mark

Write the output.

print(25 + 100**1**3 / 5)
Answer
45.0

Working (step by step)

LineStatementValues after this stepPrinted
1print(25 + 100**1**3 / 5)45.0⏎
A2.4SQP 2026-271 mark

Write the output.

text = "Drone Expo"
print(text[-2::-4])
Answer
peD

Working (step by step)

LineStatementValues after this stepPrinted
1text = "Drone Expo"text = 'Drone Expo'
2print(text[-2::-4])peD⏎
A2.5CBSE 20261 mark

Write the output.

print("the Truth".capitalize())
Answer
The truth

Working (step by step)

LineStatementValues after this stepPrinted
1print("the Truth".capitalize())The truth⏎
A2.6CBSE 20261 mark

Write the output.

print("PythonProgram"[-1:2:-2])
Answer
mroPo

Working (step by step)

LineStatementValues after this stepPrinted
1print("PythonProgram"[-1:2:-2])mroPo⏎
A2.7CBSE 20261 mark

Write the output.

print("War and Peace by Leo Tolstoy".partition("by"))
Answer
('War and Peace ', 'by', ' Leo Tolstoy')

Working (step by step)

LineStatementValues after this stepPrinted
1print("War and Peace by Leo Tolstoy".partition("by"))('War and Peace ', 'by', ' Leo Tolstoy')⏎
A2.8CBSE 20251 mark

Write the output.

print(14 % 3 ** 2 * 4)
Answer
20

Working (step by step)

LineStatementValues after this stepPrinted
1print(14 % 3 ** 2 * 4)20⏎
A2.9CBSE 20251 mark

Write the output.

L = ['TIC', 'TAC']
print(L[::-1])
Answer
['TAC', 'TIC']

Working (step by step)

LineStatementValues after this stepPrinted
1L = ['TIC', 'TAC']L = ['TIC', 'TAC']
2print(L[::-1])['TAC', 'TIC']⏎
A2.10Practice1 mark

Write the output.

print(2 ** 3 ** 2 // 5)
Answer
102

Working (step by step)

LineStatementValues after this stepPrinted
1print(2 ** 3 ** 2 // 5)102⏎
A2.11Practice1 mark

Write the output.

print("CBSE-2027".isalnum(), "CBSE2027".isalnum())
Answer
False True

Working (step by step)

LineStatementValues after this stepPrinted
1print("CBSE-2027".isalnum(), "CBSE2027".isalnum())False True⏎
A2.12Practice1 mark

Write the output.

T = (5, 10, 15, 20)
print(T[1:3] + T[-1:])
Answer
(10, 15, 20)

Working (step by step)

LineStatementValues after this stepPrinted
1T = (5, 10, 15, 20)T = (5, 10, 15, 20)
2print(T[1:3] + T[-1:])(10, 15, 20)⏎
A2.13Practice1 mark

Write the output.

print(not 5 > 3 or 4 == 4 and 7 < 2)
Answer
False

Working (step by step)

LineStatementValues after this stepPrinted
1print(not 5 > 3 or 4 == 4 and 7 < 2)False⏎
A2.14Practice1 mark

Write the output.

s = "Kendriya"
print(s[1:6:2].upper())
Answer
EDI

Working (step by step)

LineStatementValues after this stepPrinted
1s = "Kendriya"s = 'Kendriya'
2print(s[1:6:2].upper())EDI⏎
A2.15Practice1 mark

Write the output.

print(17 // 5, 17 % 5)
Answer
3 2

Working (step by step)

LineStatementValues after this stepPrinted
1print(17 // 5, 17 % 5)3 2⏎
A2.16Practice1 mark

Write the output.

print(2 + 3 * 4 ** 2)
Answer
50

Working (step by step)

LineStatementValues after this stepPrinted
1print(2 + 3 * 4 ** 2)50⏎
A2.17Practice1 mark

Write the output.

print(10 / 4, 10 // 4)
Answer
2.5 2

Working (step by step)

LineStatementValues after this stepPrinted
1print(10 / 4, 10 // 4)2.5 2⏎
A2.18Practice1 mark

Write the output.

print("KVS" * 2 + "!")
Answer
KVSKVS!

Working (step by step)

LineStatementValues after this stepPrinted
1print("KVS" * 2 + "!")KVSKVS!⏎
A2.19Practice1 mark

Write the output.

print(len("Computer Science"))
Answer
16

Working (step by step)

LineStatementValues after this stepPrinted
1print(len("Computer Science"))16⏎
A2.20Practice1 mark

Write the output.

print("Python"[1:4])
Answer
yth

Working (step by step)

LineStatementValues after this stepPrinted
1print("Python"[1:4])yth⏎
A2.21Practice1 mark

Write the output.

print("Python"[::-1])
Answer
nohtyP

Working (step by step)

LineStatementValues after this stepPrinted
1print("Python"[::-1])nohtyP⏎
A2.22Practice1 mark

Write the output.

print("Informatics"[::3])
Answer
Ioac

Working (step by step)

LineStatementValues after this stepPrinted
1print("Informatics"[::3])Ioac⏎
A2.23Practice1 mark

Write the output.

print("hello world".title())
Answer
Hello World

Working (step by step)

LineStatementValues after this stepPrinted
1print("hello world".title())Hello World⏎
A2.24Practice1 mark

Write the output.

print("Board Exam".swapcase())
Answer
bOARD eXAM

Working (step by step)

LineStatementValues after this stepPrinted
1print("Board Exam".swapcase())bOARD eXAM⏎
A2.25Practice1 mark

Write the output.

print("banana".count("an"))
Answer
2

Working (step by step)

LineStatementValues after this stepPrinted
1print("banana".count("an"))2⏎
A2.26Practice1 mark

Write the output.

print("mississippi".find("ss"))
Answer
2

Working (step by step)

LineStatementValues after this stepPrinted
1print("mississippi".find("ss"))2⏎
A2.27Practice1 mark

Write the output.

print("a-b-c".split("-"))
Answer
['a', 'b', 'c']

Working (step by step)

LineStatementValues after this stepPrinted
1print("a-b-c".split("-"))['a', 'b', 'c']⏎
A2.28Practice1 mark

Write the output.

print(" ".join(["XII", "CS"]))
Answer
XII CS

Working (step by step)

LineStatementValues after this stepPrinted
1print(" ".join(["XII", "CS"]))XII CS⏎
A2.29Practice1 mark

Write the output.

L = [3, 1, 2]
L.sort(reverse=True)
print(L)
Answer
[3, 2, 1]

Working (step by step)

LineStatementValues after this stepPrinted
1L = [3, 1, 2]L = [3, 1, 2]
2L.sort(reverse=True)L = [3, 2, 1]
3print(L)[3, 2, 1]⏎
A2.30Practice1 mark

Write the output.

L = [1, 2, 3]
L.extend([4, 5])
print(len(L))
Answer
5

Working (step by step)

LineStatementValues after this stepPrinted
1L = [1, 2, 3]L = [1, 2, 3]
2L.extend([4, 5])L = [1, 2, 3, 4, 5]
3print(len(L))5⏎
A2.31Practice1 mark

Write the output.

L = [10, 20, 30, 40]
print(L[1:3], L[-1])
Answer
[20, 30] 40

Working (step by step)

LineStatementValues after this stepPrinted
1L = [10, 20, 30, 40]L = [10, 20, 30, 40]
2print(L[1:3], L[-1])[20, 30] 40⏎
A2.32Practice1 mark

Write the output.

L = [5, 8, 5, 2]
L.remove(5)
print(L)
Answer
[8, 5, 2]

Working (step by step)

LineStatementValues after this stepPrinted
1L = [5, 8, 5, 2]L = [5, 8, 5, 2]
2L.remove(5)L = [8, 5, 2]
3print(L)[8, 5, 2]⏎
A2.33Practice1 mark

Write the output.

L = [1, 2, 3]
print(L * 2)
Answer
[1, 2, 3, 1, 2, 3]

Working (step by step)

LineStatementValues after this stepPrinted
1L = [1, 2, 3]L = [1, 2, 3]
2print(L * 2)[1, 2, 3, 1, 2, 3]⏎
A2.34Practice1 mark

Write the output.

T = (4, 9, 1)
print(max(T) - min(T))
Answer
8

Working (step by step)

LineStatementValues after this stepPrinted
1T = (4, 9, 1)T = (4, 9, 1)
2print(max(T) - min(T))8⏎
A2.35Practice1 mark

Write the output.

T = (1, 2) + (3,)
print(T)
Answer
(1, 2, 3)

Working (step by step)

LineStatementValues after this stepPrinted
1T = (1, 2) + (3,)T = (1, 2, 3)
2print(T)(1, 2, 3)⏎
A2.36Practice1 mark

Write the output.

D = {"a": 1, "b": 2}
D["c"] = 3
print(len(D), D["b"])
Answer
3 2

Working (step by step)

LineStatementValues after this stepPrinted
1D = {"a": 1, "b": 2}D = {'a': 1, 'b': 2}
2D["c"] = 3D = {'a': 1, 'b': 2, 'c': 3}
3print(len(D), D["b"])3 2⏎
A2.37Practice1 mark

Write the output.

D = {"x": 5}
print(D.get("y", 0))
Answer
0

Working (step by step)

LineStatementValues after this stepPrinted
1D = {"x": 5}D = {'x': 5}
2print(D.get("y", 0))0⏎
A2.38Practice1 mark

Write the output.

D = {1: "one", 2: "two"}
print(list(D.keys()))
Answer
[1, 2]

Working (step by step)

LineStatementValues after this stepPrinted
1D = {1: "one", 2: "two"}D = {1: 'one', 2: 'two'}
2print(list(D.keys()))[1, 2]⏎
A2.39Practice1 mark

Write the output.

print(bool(0), bool("0"))
Answer
False True

Working (step by step)

LineStatementValues after this stepPrinted
1print(bool(0), bool("0"))False True⏎
A2.40Practice1 mark

Write the output.

print(5 > 3 and 2 > 4 or not False)
Answer
True

Working (step by step)

LineStatementValues after this stepPrinted
1print(5 > 3 and 2 > 4 or not False)True⏎
A2.41Practice1 mark

Write the output.

x = 5
x += 3 * 2
print(x)
Answer
11

Working (step by step)

LineStatementValues after this stepPrinted
1x = 5x = 5
2x += 3 * 2x = 11
3print(x)11⏎
A2.42Practice1 mark

Write the output.

print(type(3 / 1))
Answer
<class 'float'>

Working (step by step)

LineStatementValues after this stepPrinted
1print(type(3 / 1))<class 'float'>⏎
A2.43Practice1 mark

Write the output.

print("5" + "5", 5 + 5)
Answer
55 10

Working (step by step)

LineStatementValues after this stepPrinted
1print("5" + "5", 5 + 5)55 10⏎
A2.44Practice1 mark

Write the output.

print(list(range(2, 11, 4)))
Answer
[2, 6, 10]

Working (step by step)

LineStatementValues after this stepPrinted
1print(list(range(2, 11, 4)))[2, 6, 10]⏎
A2.45Practice1 mark

Write the output.

print(1 + 2 * 3 ** 2)
Answer
19

Working (step by step)

LineStatementValues after this stepPrinted
1print(1 + 2 * 3 ** 2)19⏎
A2.46Practice1 mark

Write the output.

print(4 + 2 * 2 ** 2)
Answer
12

Working (step by step)

LineStatementValues after this stepPrinted
1print(4 + 2 * 2 ** 2)12⏎
A2.47Practice1 mark

Write the output.

print(10 + 1 * 4 ** 2)
Answer
26

Working (step by step)

LineStatementValues after this stepPrinted
1print(10 + 1 * 4 ** 2)26⏎
A2.48Practice1 mark

Write the output.

print(0 + 5 * 2 ** 2)
Answer
20

Working (step by step)

LineStatementValues after this stepPrinted
1print(0 + 5 * 2 ** 2)20⏎
A2.49Practice1 mark

Write the output.

print(7 + 3 * 1 ** 2)
Answer
10

Working (step by step)

LineStatementValues after this stepPrinted
1print(7 + 3 * 1 ** 2)10⏎
A2.50Practice1 mark

Write the output.

print(2 + 2 * 5 ** 2)
Answer
52

Working (step by step)

LineStatementValues after this stepPrinted
1print(2 + 2 * 5 ** 2)52⏎
A2.51Practice1 mark

Write the output.

print(23 // 4, 23 % 4)
Answer
5 3

Working (step by step)

LineStatementValues after this stepPrinted
1print(23 // 4, 23 % 4)5 3⏎
A2.52Practice1 mark

Write the output.

print(40 // 6, 40 % 6)
Answer
6 4

Working (step by step)

LineStatementValues after this stepPrinted
1print(40 // 6, 40 % 6)6 4⏎
A2.53Practice1 mark

Write the output.

print(9 // 10, 9 % 10)
Answer
0 9

Working (step by step)

LineStatementValues after this stepPrinted
1print(9 // 10, 9 % 10)0 9⏎
A2.54Practice1 mark

Write the output.

print(100 // 8, 100 % 8)
Answer
12 4

Working (step by step)

LineStatementValues after this stepPrinted
1print(100 // 8, 100 % 8)12 4⏎
A2.55Practice1 mark

Write the output.

print(15 // 15, 15 % 15)
Answer
1 0

Working (step by step)

LineStatementValues after this stepPrinted
1print(15 // 15, 15 % 15)1 0⏎
A2.56Practice1 mark

Write the output.

print(31 // 7, 31 % 7)
Answer
4 3

Working (step by step)

LineStatementValues after this stepPrinted
1print(31 // 7, 31 % 7)4 3⏎
A2.57Practice1 mark

Write the output.

print("Computer"[2:5])
Answer
mpu

Working (step by step)

LineStatementValues after this stepPrinted
1print("Computer"[2:5])mpu⏎
A2.58Practice1 mark

Write the output.

print("Kendriya"[0:4])
Answer
Kend

Working (step by step)

LineStatementValues after this stepPrinted
1print("Kendriya"[0:4])Kend⏎
A2.59Practice1 mark

Write the output.

print("Database"[4:8])
Answer
base

Working (step by step)

LineStatementValues after this stepPrinted
1print("Database"[4:8])base⏎
A2.60Practice1 mark

Write the output.

print("Network"[1:4])
Answer
etw

Working (step by step)

LineStatementValues after this stepPrinted
1print("Network"[1:4])etw⏎
A2.61Practice1 mark

Write the output.

print("Vidyalaya"[3:7])
Answer
yala

Working (step by step)

LineStatementValues after this stepPrinted
1print("Vidyalaya"[3:7])yala⏎
A2.62Practice1 mark

Write the output.

print("Function"[2:6])
Answer
ncti

Working (step by step)

LineStatementValues after this stepPrinted
1print("Function"[2:6])ncti⏎
A2.63Practice1 mark

Write the output.

print("Dictionary"[4:9])
Answer
ionar

Working (step by step)

LineStatementValues after this stepPrinted
1print("Dictionary"[4:9])ionar⏎
A2.64Practice1 mark

Write the output.

print("Sangathan"[1:5])
Answer
anga

Working (step by step)

LineStatementValues after this stepPrinted
1print("Sangathan"[1:5])anga⏎
A2.65Practice1 mark

Write the output.

print("Computer"[::-1])
Answer
retupmoC

Working (step by step)

LineStatementValues after this stepPrinted
1print("Computer"[::-1])retupmoC⏎
A2.66Practice1 mark

Write the output.

print("Science"[::-2])
Answer
eniS

Working (step by step)

LineStatementValues after this stepPrinted
1print("Science"[::-2])eniS⏎
A2.67Practice1 mark

Write the output.

print("Dictionary"[::3])
Answer
Dtny

Working (step by step)

LineStatementValues after this stepPrinted
1print("Dictionary"[::3])Dtny⏎
A2.68Practice1 mark

Write the output.

print("Examination"[::-3])
Answer
ntix

Working (step by step)

LineStatementValues after this stepPrinted
1print("Examination"[::-3])ntix⏎
A2.69Practice1 mark

Write the output.

print("Keyboard"[::2])
Answer
Kyor

Working (step by step)

LineStatementValues after this stepPrinted
1print("Keyboard"[::2])Kyor⏎
A2.70Practice1 mark

Write the output.

print("Monitor"[::-1])
Answer
rotinoM

Working (step by step)

LineStatementValues after this stepPrinted
1print("Monitor"[::-1])rotinoM⏎
A2.71Practice1 mark

Write the output.

print("new delhi".title())
Answer
New Delhi

Working (step by step)

LineStatementValues after this stepPrinted
1print("new delhi".title())New Delhi⏎
A2.72Practice1 mark

Write the output.

print("CLASS xii".lower())
Answer
class xii

Working (step by step)

LineStatementValues after this stepPrinted
1print("CLASS xii".lower())class xii⏎
A2.73Practice1 mark

Write the output.

print("sample paper".upper())
Answer
SAMPLE PAPER

Working (step by step)

LineStatementValues after this stepPrinted
1print("sample paper".upper())SAMPLE PAPER⏎
A2.74Practice1 mark

Write the output.

print("pYTHON".capitalize())
Answer
Python

Working (step by step)

LineStatementValues after this stepPrinted
1print("pYTHON".capitalize())Python⏎
A2.75Practice1 mark

Write the output.

print("data file".title())
Answer
Data File

Working (step by step)

LineStatementValues after this stepPrinted
1print("data file".title())Data File⏎
A2.76Practice1 mark

Write the output.

print("STACK".lower())
Answer
stack

Working (step by step)

LineStatementValues after this stepPrinted
1print("STACK".lower())stack⏎
A2.77Practice1 mark

Write the output.

print("my sql".upper())
Answer
MY SQL

Working (step by step)

LineStatementValues after this stepPrinted
1print("my sql".upper())MY SQL⏎
A2.78Practice1 mark

Write the output.

print("half yearly".capitalize())
Answer
Half yearly

Working (step by step)

LineStatementValues after this stepPrinted
1print("half yearly".capitalize())Half yearly⏎
A2.79Practice1 mark

Write the output.

print("programme".count("m"), "programme".find("m"))
Answer
2 6

Working (step by step)

LineStatementValues after this stepPrinted
1print("programme".count("m"), "programme".find("m"))2 6⏎
A2.80Practice1 mark

Write the output.

print("committee".count("t"), "committee".find("t"))
Answer
2 5

Working (step by step)

LineStatementValues after this stepPrinted
1print("committee".count("t"), "committee".find("t"))2 5⏎
A2.81Practice1 mark

Write the output.

print("success".count("s"), "success".find("s"))
Answer
3 0

Working (step by step)

LineStatementValues after this stepPrinted
1print("success".count("s"), "success".find("s"))3 0⏎
A2.82Practice1 mark

Write the output.

print("assessment".count("ss"), "assessment".find("ss"))
Answer
2 1

Working (step by step)

LineStatementValues after this stepPrinted
1print("assessment".count("ss"), "assessment".find("ss"))2 1⏎
A2.83Practice1 mark

Write the output.

print("referee".count("e"), "referee".find("e"))
Answer
4 1

Working (step by step)

LineStatementValues after this stepPrinted
1print("referee".count("e"), "referee".find("e"))4 1⏎
A2.84Practice1 mark

Write the output.

print("parallel".count("l"), "parallel".find("l"))
Answer
3 4

Working (step by step)

LineStatementValues after this stepPrinted
1print("parallel".count("l"), "parallel".find("l"))3 4⏎
A2.85Practice1 mark

Write the output.

L = [5, 10, 15]
L.append(20)
print(L[-2:])
Answer
[15, 20]

Working (step by step)

LineStatementValues after this stepPrinted
1L = [5, 10, 15]L = [5, 10, 15]
2L.append(20)L = [5, 10, 15, 20]
3print(L[-2:])[15, 20]⏎
A2.86Practice1 mark

Write the output.

L = [4, 8, 12, 16]
L.pop(1)
print(L)
Answer
[4, 12, 16]

Working (step by step)

LineStatementValues after this stepPrinted
1L = [4, 8, 12, 16]L = [4, 8, 12, 16]
2L.pop(1)L = [4, 12, 16]
3print(L)[4, 12, 16]⏎
A2.87Practice1 mark

Write the output.

L = [9, 3, 6]
L.insert(0, 1)
print(L[:2])
Answer
[1, 9]

Working (step by step)

LineStatementValues after this stepPrinted
1L = [9, 3, 6]L = [9, 3, 6]
2L.insert(0, 1)L = [1, 9, 3, 6]
3print(L[:2])[1, 9]⏎
A2.88Practice1 mark

Write the output.

L = [2, 4]
L.extend([6, 8])
print(L[1:3])
Answer
[4, 6]

Working (step by step)

LineStatementValues after this stepPrinted
1L = [2, 4]L = [2, 4]
2L.extend([6, 8])L = [2, 4, 6, 8]
3print(L[1:3])[4, 6]⏎
A2.89Practice1 mark

Write the output.

L = [7, 1, 5]
L.sort()
print(L[0], L[-1])
Answer
1 7

Working (step by step)

LineStatementValues after this stepPrinted
1L = [7, 1, 5]L = [7, 1, 5]
2L.sort()L = [1, 5, 7]
3print(L[0], L[-1])1 7⏎
A2.90Practice1 mark

Write the output.

L = [1, 2, 3, 4]
L.reverse()
print(L[1])
Answer
3

Working (step by step)

LineStatementValues after this stepPrinted
1L = [1, 2, 3, 4]L = [1, 2, 3, 4]
2L.reverse()L = [4, 3, 2, 1]
3print(L[1])3⏎
A2.91Practice1 mark

Write the output.

L = ["a", "b", "c"]
print(L.index("c"), len(L))
Answer
2 3

Working (step by step)

LineStatementValues after this stepPrinted
1L = ["a", "b", "c"]L = ['a', 'b', 'c']
2print(L.index("c"), len(L))2 3⏎
A2.92Practice1 mark

Write the output.

L = [3, 3, 4]
print(L.count(3) + sum(L))
Answer
12

Working (step by step)

LineStatementValues after this stepPrinted
1L = [3, 3, 4]L = [3, 3, 4]
2print(L.count(3) + sum(L))12⏎
A2.93Practice1 mark

Write the output.

print(len([14, 3, 27]), max([14, 3, 27]), min([14, 3, 27]))
Answer
3 27 3

Working (step by step)

LineStatementValues after this stepPrinted
1print(len([14, 3, 27]), max([14, 3, 27]), min([14, 3, 27]))3 27 3⏎
A2.94Practice1 mark

Write the output.

print(len((8, 8, 2, 5)), max((8, 8, 2, 5)), min((8, 8, 2, 5)))
Answer
4 8 2

Working (step by step)

LineStatementValues after this stepPrinted
1print(len((8, 8, 2, 5)), max((8, 8, 2, 5)), min((8, 8, 2, 5)))4 8 2⏎
A2.95Practice1 mark

Write the output.

print(len([0, -4, 9]), max([0, -4, 9]), min([0, -4, 9]))
Answer
3 9 -4

Working (step by step)

LineStatementValues after this stepPrinted
1print(len([0, -4, 9]), max([0, -4, 9]), min([0, -4, 9]))3 9 -4⏎
A2.96Practice1 mark

Write the output.

print(len((100, 50)), max((100, 50)), min((100, 50)))
Answer
2 100 50

Working (step by step)

LineStatementValues after this stepPrinted
1print(len((100, 50)), max((100, 50)), min((100, 50)))2 100 50⏎
A2.97Practice1 mark

Write the output.

D = {"x": 4, "y": 6}
print(D.get("y"), len(D))
Answer
6 2

Working (step by step)

LineStatementValues after this stepPrinted
1D = {"x": 4, "y": 6}D = {'x': 4, 'y': 6}
2print(D.get("y"), len(D))6 2⏎
A2.98Practice1 mark

Write the output.

D = {"a": 1}
D["b"] = 5
print(sorted(D), sum(D.values()))
Answer
['a', 'b'] 6

Working (step by step)

LineStatementValues after this stepPrinted
1D = {"a": 1}D = {'a': 1}
2D["b"] = 5D = {'a': 1, 'b': 5}
3print(sorted(D), sum(D.values()))['a', 'b'] 6⏎
A2.99Practice1 mark

Write the output.

D = {1: 10, 2: 20}
print(D[2] - D[1], 3 in D)
Answer
10 False

Working (step by step)

LineStatementValues after this stepPrinted
1D = {1: 10, 2: 20}D = {1: 10, 2: 20}
2print(D[2] - D[1], 3 in D)10 False⏎
A2.100Practice1 mark

Write the output.

D = {"p": 9}
D.update({"q": 1})
print(list(D.values()))
Answer
[9, 1]

Working (step by step)

LineStatementValues after this stepPrinted
1D = {"p": 9}D = {'p': 9}
2D.update({"q": 1})D = {'p': 9, 'q': 1}
3print(list(D.values()))[9, 1]⏎
A2.101Practice1 mark

Write the output.

print(7 > 5 and 2 > 9)
Answer
False

Working (step by step)

LineStatementValues after this stepPrinted
1print(7 > 5 and 2 > 9)False⏎
A2.102Practice1 mark

Write the output.

print(not 4 == 4 or 3 < 8)
Answer
True

Working (step by step)

LineStatementValues after this stepPrinted
1print(not 4 == 4 or 3 < 8)True⏎
A2.103Practice1 mark

Write the output.

print(10 >= 10 and not 6 < 2)
Answer
True

Working (step by step)

LineStatementValues after this stepPrinted
1print(10 >= 10 and not 6 < 2)True⏎
A2.104Practice1 mark

Write the output.

print(5 != 5 or 1 > 0 and 2 > 3)
Answer
False

Working (step by step)

LineStatementValues after this stepPrinted
1print(5 != 5 or 1 > 0 and 2 > 3)False⏎
A2.105Practice1 mark

Write the output.

print(not (3 > 1 and 2 > 1))
Answer
False

Working (step by step)

LineStatementValues after this stepPrinted
1print(not (3 > 1 and 2 > 1))False⏎
A2.106Practice1 mark

Write the output.

print(8 % 2 == 0 or 9 % 2 == 0)
Answer
True

Working (step by step)

LineStatementValues after this stepPrinted
1print(8 % 2 == 0 or 9 % 2 == 0)True⏎
A3Database and SQL MCQ1 mark · 104 questions
A3.1SQP 2026-271 mark

A column in one table that matches the primary key of another table is called a ...

Answer

(c) Foreign key A foreign key links a table to the primary key of another table.

A3.2SQP 2026-271 mark

Which MySQL query shows the employees whose salary is from 90,000 to 1,00,000, both limits included?

Answer

(c) SELECT * FROM Employees WHERE salary BETWEEN 90000 AND 100000; BETWEEN includes both limits.

A3.3SQP 2026-271 mark

The set of values that an attribute is allowed to take is called its ...

Answer

(a) Domain The domain of an attribute is its set of allowed values, e.g. {'M', 'F'}.

A3.4SQP 2026-271 mark

Which property of a relation does not change when a new row is inserted?

Answer

(b) Degree Degree is the number of columns.

A3.5SQP 2026-271 mark

Which MySQL command removes the attribute Age from the table Student?

Answer

(a) ALTER TABLE Student DROP COLUMN Age; Changing the structure needs ALTER TABLE; DROP COLUMN removes a column.

A3.6CBSE 20261 mark

A table has two candidate keys, one of which is chosen as the primary key. How many alternate keys does the table have?

Answer

(b) 1 Alternate keys = candidate keys - primary key.

A3.7CBSE 20261 mark

Which SQL command can change the degree of an existing relation?

Answer

(b) ALTER TABLE ALTER TABLE adds or drops columns.

A3.8CBSE 20261 mark

A relation has 2 tuples and 3 attributes. If 2 attributes are deleted and 4 tuples are added, what is the cardinality?

Answer

(c) 6 2 + 4 = 6 rows. The degree becomes 1.

A3.9CBSE 20261 mark

Which aggregate function returns the smallest value of a column?

Answer

(a) MIN() MIN() gives the smallest value; MAX() gives the largest.

A3.10CBSE 20251 mark

Which constraint makes sure that no two rows have the same value in a column?

Answer

(a) UNIQUE UNIQUE does not allow repeated values in the column.

A3.11CBSE 20251 mark

Which of the following is a DML command?

Answer

(a) UPDATE DML commands change the data: INSERT, UPDATE, DELETE. CREATE, ALTER and DROP are DDL.

A3.12CBSE 20251 mark

Which aggregate function counts the non-NULL values of a column?

Answer

(b) count() COUNT(column) counts only the values that are not NULL; COUNT(*) counts all rows.

A3.13CBSE 20251 mark

Table A has 6 rows and 3 columns; table B has 5 rows and 2 columns. Their Cartesian product has ...

Answer

(a) 30 rows and 5 columns Rows multiply, columns add.

A3.14CBSE 20251 mark

Values of which MySQL data type are written without quotes?

Answer

(c) FLOAT Numbers (INT, FLOAT, DECIMAL) are written without quotes; text and dates need quotes.

A3.15Practice1 mark

A row of a relation is called a ...

Answer

(b) tuple Each row holds one record and is called a tuple.

A3.16Practice1 mark

A column of a relation is called a/an ...

Answer

(b) attribute A column is an attribute; a row is a tuple.

A3.17Practice1 mark

The number of rows in a relation is called its ...

Answer

(b) cardinality Cardinality = number of rows; degree = number of columns.

A3.18Practice1 mark

How many primary keys can a table have?

Answer

(a) Only one A table can have many candidate keys but one primary key.

A3.19Practice1 mark

Candidate keys that are not chosen as the primary key are called ...

Answer

(b) alternate keys The remaining candidate keys are called alternate keys.

A3.20Practice1 mark

Which of the following is a DDL command?

Answer

(c) CREATE DDL commands define the structure: CREATE, ALTER, DROP.

A3.21Practice1 mark

Which command removes all the rows of a table but keeps the table?

Answer

(b) DELETE FROM DELETE FROM table; without WHERE removes all the rows but the empty table remains.

A3.22Practice1 mark

Which command removes a table together with its structure?

Answer

(b) DROP TABLE DROP TABLE removes the table itself, with its structure and data.

A3.23Practice1 mark

Which clause arranges the output in sorted order?

Answer

(b) ORDER BY ORDER BY column sorts the result (ASC by default, DESC for descending).

A3.24Practice1 mark

The default order of the ORDER BY clause is ...

Answer

(a) ascending Write DESC for descending order.

A3.25Practice1 mark

Which keyword removes duplicate values from the output of SELECT?

Answer

(b) DISTINCT SELECT DISTINCT city shows each city only once.

A3.26Practice1 mark

In a LIKE pattern, which symbol stands for exactly one character?

Answer

(b) _ _ stands for exactly one character; % stands for any number of characters.

A3.27Practice1 mark

In a LIKE pattern, which symbol stands for zero or more characters?

Answer

(a) % % stands for zero or more characters; _ stands for exactly one.

A3.28Practice1 mark

Which is the correct way to find rows where Phone has no value?

Answer

(b) WHERE Phone IS NULL NULL means unknown, so = NULL never matches; IS NULL is used.

A3.29Practice1 mark

Which clause puts a condition on groups made by GROUP BY?

Answer

(b) HAVING HAVING filters the groups; WHERE filters the rows before grouping.

A3.30Practice1 mark

COUNT(*) counts ...

Answer

(b) all the rows COUNT(*) counts every row, including rows that have NULL values.

A3.31Practice1 mark

Which data type is best for a date of birth?

Answer

(b) DATE DATE stores dates in the form 'YYYY-MM-DD' and allows date functions.

A3.32Practice1 mark

A CHAR(10) column that stores 'Ram' uses space for ...

Answer

(b) 10 characters CHAR has a fixed length.

A3.33Practice1 mark

A VARCHAR(10) column that stores 'Ram' uses space for ...

Answer

(a) 3 characters VARCHAR has a variable length.

A3.34Practice1 mark

Which command shows the structure of a table?

Answer

(b) DESC DESC or DESCRIBE.

A3.35Practice1 mark

Which command opens a database for use?

Answer

(b) USE USE school; makes school the current database.

A3.36Practice1 mark

Which command lists all the tables of the current database?

Answer

(a) SHOW TABLES; SHOW TABLES; lists the tables of the database in use.

A3.37Practice1 mark

Which command changes the data stored in existing rows?

Answer

(b) UPDATE UPDATE ... SET ... WHERE changes values in existing rows.

A3.38Practice1 mark

Which command adds a new column to an existing table?

Answer

(b) ALTER TABLE ... ADD ALTER TABLE STUDENT ADD Phone VARCHAR(10); adds a column.

A3.39Practice1 mark

In which join does the common column appear only once in the output?

Answer

(c) Natural join NATURAL JOIN joins on the common column and shows it only once; an equi-join shows it twice.

A3.40Practice1 mark

The Cartesian product of a table with 4 rows and a table with 3 rows has ______ rows.

Answer

(b) 12 4 x 3 = 12.

A3.41Practice1 mark

A PRIMARY KEY constraint is the same as ...

Answer

(a) UNIQUE + NOT NULL A primary key value must be unique and cannot be NULL.

A3.42Practice1 mark

Which method runs an SQL query from a Python program?

Answer

(b) execute() It is a method of the cursor object.

A3.43Practice1 mark

Which method saves the changes made by INSERT, UPDATE or DELETE permanently?

Answer

(b) commit() It is a method of the connection object.

A3.44Practice1 mark

fetchall() returns ...

Answer

(b) a list of tuples Each tuple is one row.

A3.45Practice1 mark

A relation has 4 tuples and 5 attributes. 3 more tuples are added and 1 attribute is removed. What is its degree now?

Answer

(c) 4 Degree = 5 - 1 = 4 columns; cardinality = 4 + 3 = 7 rows.

A3.46Practice1 mark

A relation has 4 tuples and 5 attributes. 3 more tuples are added and 1 attribute is removed. What is its cardinality now?

Answer

(d) 7 Degree = 5 - 1 = 4 columns; cardinality = 4 + 3 = 7 rows.

A3.47Practice1 mark

A relation has 10 tuples and 3 attributes. 5 more tuples are added and 0 attributes are removed. What is its cardinality now?

Answer

(b) 15 Degree = 3 - 0 = 3 columns; cardinality = 10 + 5 = 15 rows.

A3.48Practice1 mark

A relation has 10 tuples and 3 attributes. 0 more tuples are added and 1 attribute is removed. What is its degree now?

Answer

(a) 2 Degree = 3 - 1 = 2 columns; cardinality = 10 + 0 = 10 rows.

A3.49Practice1 mark

A relation has 6 tuples and 6 attributes. 2 more tuples are added and 2 attributes are removed. What is its degree now?

Answer

(a) 4 Degree = 6 - 2 = 4 columns; cardinality = 6 + 2 = 8 rows.

A3.50Practice1 mark

A relation has 6 tuples and 6 attributes. 2 more tuples are added and 2 attributes are removed. What is its cardinality now?

Answer

(d) 8 Degree = 6 - 2 = 4 columns; cardinality = 6 + 2 = 8 rows.

A3.51Practice1 mark

A relation has 8 tuples and 4 attributes. 4 more tuples are added and 1 attribute is removed. What is its cardinality now?

Answer

(c) 12 Degree = 4 - 1 = 3 columns; cardinality = 8 + 4 = 12 rows.

A3.52Practice1 mark

A relation has 8 tuples and 4 attributes. 4 more tuples are added and 1 attribute is removed. What is its degree now?

Answer

(d) 3 Degree = 4 - 1 = 3 columns; cardinality = 8 + 4 = 12 rows.

A3.53Practice1 mark

A relation has 3 tuples and 7 attributes. 9 more tuples are added and 3 attributes are removed. What is its degree now?

Answer

(d) 4 Degree = 7 - 3 = 4 columns; cardinality = 3 + 9 = 12 rows.

A3.54Practice1 mark

A relation has 3 tuples and 7 attributes. 9 more tuples are added and 3 attributes are removed. What is its cardinality now?

Answer

(a) 12 Degree = 7 - 3 = 4 columns; cardinality = 3 + 9 = 12 rows.

A3.55Practice1 mark

A relation has 12 tuples and 5 attributes. 1 more tuples are added and 2 attributes are removed. What is its degree now?

Answer

(a) 3 Degree = 5 - 2 = 3 columns; cardinality = 12 + 1 = 13 rows.

A3.56Practice1 mark

A relation has 12 tuples and 5 attributes. 1 more tuples are added and 2 attributes are removed. What is its cardinality now?

Answer

(b) 13 Degree = 5 - 2 = 3 columns; cardinality = 12 + 1 = 13 rows.

A3.57Practice1 mark

A relation has 5 tuples and 2 attributes. 5 more tuples are added and 0 attributes are removed. What is its cardinality now?

Answer

(d) 10 Degree = 2 - 0 = 2 columns; cardinality = 5 + 5 = 10 rows.

A3.58Practice1 mark

A relation has 7 tuples and 8 attributes. 0 more tuples are added and 4 attributes are removed. What is its degree now?

Answer

(b) 4 Degree = 8 - 4 = 4 columns; cardinality = 7 + 0 = 7 rows.

A3.59Practice1 mark

A relation has 9 tuples and 6 attributes. 6 more tuples are added and 3 attributes are removed. What is its cardinality now?

Answer

(b) 15 Degree = 6 - 3 = 3 columns; cardinality = 9 + 6 = 15 rows.

A3.60Practice1 mark

A relation has 2 tuples and 9 attributes. 8 more tuples are added and 5 attributes are removed. What is its degree now?

Answer

(b) 4 Degree = 9 - 5 = 4 columns; cardinality = 2 + 8 = 10 rows.

A3.61Practice1 mark

Table P has 3 rows and 2 columns. Table Q has 4 rows and 3 columns. How many rows does their Cartesian product have?

Answer

(c) 12 Rows multiply (3 x 4); columns add (2 + 3).

A3.62Practice1 mark

Table P has 3 rows and 2 columns. Table Q has 4 rows and 3 columns. How many columns does their Cartesian product have?

Answer

(b) 5 Rows multiply (3 x 4); columns add (2 + 3).

A3.63Practice1 mark

Table P has 5 rows and 4 columns. Table Q has 2 rows and 2 columns. How many rows does their Cartesian product have?

Answer

(c) 10 Rows multiply (5 x 2); columns add (4 + 2).

A3.64Practice1 mark

Table P has 5 rows and 4 columns. Table Q has 2 rows and 2 columns. How many columns does their Cartesian product have?

Answer

(a) 6 Rows multiply (5 x 2); columns add (4 + 2).

A3.65Practice1 mark

Table P has 6 rows and 3 columns. Table Q has 3 rows and 5 columns. How many rows does their Cartesian product have?

Answer

(d) 18 Rows multiply (6 x 3); columns add (3 + 5).

A3.66Practice1 mark

Table P has 7 rows and 2 columns. Table Q has 2 rows and 6 columns. How many columns does their Cartesian product have?

Answer

(a) 8 Rows multiply (7 x 2); columns add (2 + 6).

A3.67Practice1 mark

Table P has 10 rows and 3 columns. Table Q has 3 rows and 2 columns. How many rows does their Cartesian product have?

Answer

(a) 30 Rows multiply (10 x 3); columns add (3 + 2).

A3.68Practice1 mark

Table P has 4 rows and 4 columns. Table Q has 4 rows and 4 columns. How many columns does their Cartesian product have?

Answer

(a) 8 Rows multiply (4 x 4); columns add (4 + 4).

A3.69Practice1 mark

Table P has 8 rows and 5 columns. Table Q has 5 rows and 1 columns. How many rows does their Cartesian product have?

Answer

(c) 40 Rows multiply (8 x 5); columns add (5 + 1).

A3.70Practice1 mark

Table P has 9 rows and 2 columns. Table Q has 2 rows and 3 columns. How many columns does their Cartesian product have?

Answer

(a) 5 Rows multiply (9 x 2); columns add (2 + 3).

A3.71Practice1 mark

The column marks of a table has the values 40, NULL, 60, 80. What does SELECT COUNT(marks) FROM t; return?

Answer

(d) 3 COUNT(*) counts every row. The other aggregate functions skip NULL.

A3.72Practice1 mark

The column marks of a table has the values 40, NULL, 60, 80. What does SELECT COUNT(*) FROM t; return?

Answer

(b) 4 COUNT(*) counts every row. The other aggregate functions skip NULL.

A3.73Practice1 mark

The column marks of a table has the values 10, 20, NULL, 30. What does SELECT SUM(marks) FROM t; return?

Answer

(c) 60 COUNT(*) counts every row. The other aggregate functions skip NULL.

A3.74Practice1 mark

The column marks of a table has the values 10, 20, NULL, 30. What does SELECT AVG(marks) FROM t; return?

Answer

(b) 20 COUNT(*) counts every row. The other aggregate functions skip NULL.

A3.75Practice1 mark

The column marks of a table has the values 55, 90, NULL, 70. What does SELECT MAX(marks) FROM t; return?

Answer

(a) 90 COUNT(*) counts every row. The other aggregate functions skip NULL.

A3.76Practice1 mark

The column marks of a table has the values 55, 90, NULL, 70. What does SELECT MIN(marks) FROM t; return?

Answer

(a) 55 COUNT(*) counts every row. The other aggregate functions skip NULL.

A3.77Practice1 mark

The column marks of a table has the values NULL, NULL, 50. What does SELECT COUNT(marks) FROM t; return?

Answer

(d) 1 COUNT(*) counts every row. The other aggregate functions skip NULL.

A3.78Practice1 mark

The column marks of a table has the values 25, 75, NULL. What does SELECT AVG(marks) FROM t; return?

Answer

(c) 50 COUNT(*) counts every row. The other aggregate functions skip NULL.

A3.79Practice1 mark

The column marks of a table has the values 5, 5, NULL, 5, 5. What does SELECT SUM(marks) FROM t; return?

Answer

(d) 20 COUNT(*) counts every row. The other aggregate functions skip NULL.

A3.80Practice1 mark

The column marks of a table has the values NULL, 12, 12, NULL. What does SELECT COUNT(*) FROM t; return?

Answer

(c) 4 COUNT(*) counts every row. The other aggregate functions skip NULL.

A3.81Practice1 mark

Which of these names is selected by the condition name LIKE 'S_m%'?

Answer

(a) Suman % stands for any number of characters and _ for exactly one character.

A3.82Practice1 mark

Which of these names is selected by the condition name LIKE '%an'?

Answer

(b) Aman % stands for any number of characters and _ for exactly one character.

A3.83Practice1 mark

Which of these names is selected by the condition name LIKE '_a%'?

Answer

(d) Ravi % stands for any number of characters and _ for exactly one character.

A3.84Practice1 mark

Which of these names is selected by the condition name LIKE 'A%a'?

Answer

(a) Anita % stands for any number of characters and _ for exactly one character.

A3.85Practice1 mark

Which of these names is selected by the condition name LIKE '%e%'?

Answer

(a) Neha % stands for any number of characters and _ for exactly one character.

A3.86Practice1 mark

Which of these names is selected by the condition name LIKE '____'?

Answer

(d) Asha % stands for any number of characters and _ for exactly one character.

A3.87Practice1 mark

Which of these names is selected by the condition name LIKE 'R%'?

Answer

(b) Ritu % stands for any number of characters and _ for exactly one character.

A3.88Practice1 mark

Which of these names is selected by the condition name LIKE '%i'?

Answer

(b) Ravi % stands for any number of characters and _ for exactly one character.

A3.89Practice1 mark

Which of these names is selected by the condition name LIKE '_i%a'?

Answer

(d) Tina % stands for any number of characters and _ for exactly one character.

A3.90Practice1 mark

Which of these names is selected by the condition name LIKE '%sh%'?

Answer

(d) Asha % stands for any number of characters and _ for exactly one character.

A3.91Practice1 mark

A column x has the values 10, 20, 30, 40, 50. How many rows satisfy WHERE x BETWEEN 20 AND 40?

Answer

(c) 3 BETWEEN includes both of its limits.

A3.92Practice1 mark

A column x has the values 5, 15, 25, 35. How many rows satisfy WHERE x IN (5, 25, 45)?

Answer

(b) 2 BETWEEN includes both of its limits.

A3.93Practice1 mark

A column x has the values 33, 60, 75, 90, 100. How many rows satisfy WHERE x BETWEEN 60 AND 90?

Answer

(d) 3 BETWEEN includes both of its limits.

A3.94Practice1 mark

A column x has the values 1, 2, 3, 4, 5, 6. How many rows satisfy WHERE x NOT IN (2, 4)?

Answer

(b) 4 BETWEEN includes both of its limits.

A3.95Practice1 mark

A column x has the values 12, 18, 24, 30. How many rows satisfy WHERE x NOT BETWEEN 18 AND 24?

Answer

(b) 2 BETWEEN includes both of its limits.

A3.96Practice1 mark

A column x has the values 7, 14, 21, 28, 35. How many rows satisfy WHERE x > 14 AND x <= 28?

Answer

(a) 2 BETWEEN includes both of its limits.

A3.97Practice1 mark

Which clause is used with aggregate functions to make one group for every city?

Answer

(b) GROUP BY city GROUP BY city makes one group per city; the aggregate is worked out for each group.

A3.98Practice1 mark

Which command makes RNo the primary key of an existing table STUDENT?

Answer

(a) ALTER TABLE STUDENT ADD PRIMARY KEY (RNo); ALTER TABLE ... ADD PRIMARY KEY (column) adds a primary key to an existing table.

A3.99Practice1 mark

Which of the following is not a constraint?

Answer

(d) ORDER BY ORDER BY is a clause of SELECT.

A3.100Practice1 mark

Which command lists all the databases on the server?

Answer

(a) SHOW DATABASES; SHOW DATABASES; lists the databases; SHOW TABLES; lists the tables of the current database.

A3.101Practice1 mark

In SELECT name AS Student FROM s; the word Student is ...

Answer

(b) an alias (temporary heading) for the column AS gives a temporary heading (alias) to the column in the output.

A3.102Practice1 mark

Which operator is used in the join condition of an equi join?

Answer

(b) = An equi-join matches rows with =, e.g. A.ID = B.ID.

A3.103Practice1 mark

Which command removes the database school completely?

Answer

(b) DROP DATABASE school; DROP DATABASE removes the database with all its tables.

A3.104Practice1 mark

In ORDER BY marks DESC, the word DESC means ...

Answer

(b) descending order DESC sorts from the largest to the smallest; ASC (default) sorts from the smallest.

A4Computer networks MCQ1 mark · 64 questions
A4.1SQP 2026-271 mark

Which medium is used for long-distance communication where line of sight is not possible?

Answer

(c) Radio waves Radio waves spread in all directions and pass through walls, so no line of sight is needed.

A4.2SQP 2026-271 mark

Every network interface card (NIC) comes with its own ______ address.

Answer

(c) Physical (MAC) Each NIC has a unique 48-bit physical (MAC) address burnt in by the maker.

A4.3SQP 2026-271 mark

In ______ switching, a dedicated path is set up between sender and receiver before the data transfer starts.

Answer

(c) Circuit In circuit switching (as in old telephone calls) a fixed path is reserved before talking starts.

A4.4CBSE 20261 mark

With respect to computer networks, which is the correct expanded form of RJ45?

Answer

(d) Registered Jack 45 RJ45 = Registered Jack 45, the connector used on Ethernet cables.

A4.5CBSE 20261 mark

Which network device serves as the entry and exit point of a network, as all data coming in or going out must pass through it?

Answer

(b) Gateway A gateway is the entry and exit point of a network and connects it to other networks.

A4.6CBSE 20261 mark

Expand XML.

Answer

(a) eXtensible Markup Language XML = eXtensible Markup Language, used to store and carry data with user-defined tags.

A4.7CBSE 20251 mark

Which networking device is used to regenerate and transmit a weakened signal ahead?

Answer

(c) Repeater A repeater boosts (regenerates) a weak signal so it can travel further.

A4.8CBSE 20251 mark

Which protocol is used to make phone calls over the Internet?

Answer

(d) VoIP Voice over Internet Protocol.

A4.9CBSE 20251 mark

Expand ARPANET.

Answer

(a) Advanced Research Projects Agency Network ARPANET = Advanced Research Projects Agency Network, the first network that grew into the Internet.

A4.10Practice1 mark

Which device connects computers in a LAN and sends data only to the intended computer?

Answer

(b) Switch A switch learns the MAC addresses and sends data only to the destination computer.

A4.11Practice1 mark

Which protocol is used for sending e-mail?

Answer

(b) SMTP Simple Mail Transfer Protocol.

A4.12Practice1 mark

A network that covers one city is called a ...

Answer

(b) MAN Metropolitan Area Network.

A4.13Practice1 mark

In which topology does the failure of the central device stop the whole network?

Answer

(b) Star In a star, all computers depend on the central hub or switch.

A4.14Practice1 mark

Which wired medium gives the highest speed and is not affected by electrical interference?

Answer

(c) Optical fibre Optical fibre carries light, so it is very fast and free from electrical interference.

A4.15Practice1 mark

A network of computers inside one school building is a ...

Answer

(a) LAN Local Area Network.

A4.16Practice1 mark

A phone connected to a Bluetooth headset forms a ...

Answer

(d) PAN Personal Area Network.

A4.17Practice1 mark

The Internet is the largest example of a ...

Answer

(c) WAN The Internet connects networks all over the world, so it is a WAN.

A4.18Practice1 mark

Which device changes digital signals to analog signals and back?

Answer

(a) Modem MOdulator-DEModulator.

A4.19Practice1 mark

Which device connects different networks and chooses the best path for data?

Answer

(b) Router A router connects networks and picks the best route for each packet.

A4.20Practice1 mark

Which device sends the data it receives to all the connected computers?

Answer

(a) Hub A hub broadcasts data to every port, unlike a switch.

A4.21Practice1 mark

Which protocol is used to transfer files between computers?

Answer

(a) FTP File Transfer Protocol.

A4.22Practice1 mark

Which protocol is used to receive e-mail from the mail server?

Answer

(b) POP3 Post Office Protocol version 3.

A4.23Practice1 mark

Which protocol is used for secure web pages, such as online payment?

Answer

(b) HTTPS The S stands for Secure.

A4.24Practice1 mark

Which protocol is used to log in to a remote computer?

Answer

(a) TELNET TELNET lets a user log in to and work on a remote computer.

A4.25Practice1 mark

Expand TCP.

Answer

(b) Transmission Control Protocol TCP = Transmission Control Protocol; it breaks data into packets and makes sure they arrive correctly.

A4.26Practice1 mark

Expand HTTP.

Answer

(a) HyperText Transfer Protocol HTTP = HyperText Transfer Protocol, used to transfer web pages.

A4.27Practice1 mark

Expand URL.

Answer

(b) Uniform Resource Locator URL = Uniform Resource Locator, the address of a web page.

A4.28Practice1 mark

Expand WWW.

Answer

(a) World Wide Web WWW = World Wide Web, the system of linked web pages on the Internet.

A4.29Practice1 mark

Expand NIC.

Answer

(b) Network Interface Card NIC = Network Interface Card, which connects a computer to a network.

A4.30Practice1 mark

Expand MAC in MAC address.

Answer

(a) Media Access Control MAC = Media Access Control.

A4.31Practice1 mark

An IPv4 address has ______ bits.

Answer

(b) 32 IPv6 has 128 bits.

A4.32Practice1 mark

A MAC address has ______ bits.

Answer

(b) 48 It is written as 6 pairs of hexadecimal digits.

A4.33Practice1 mark

Bandwidth is measured in ...

Answer

(a) Hertz Bandwidth (range of frequencies) is measured in Hertz; data rate is measured in bps.

A4.34Practice1 mark

Data transfer rate is measured in ...

Answer

(b) bps bits per second: Kbps, Mbps, Gbps.

A4.35Practice1 mark

Which medium carries data in the form of light?

Answer

(c) Optical fibre Optical fibre sends data as pulses of light.

A4.36Practice1 mark

A TV remote control uses ...

Answer

(c) infrared waves A TV remote uses infrared waves, which need line of sight and work over short distances.

A4.37Practice1 mark

Which wireless medium needs the sending and receiving towers to be in line of sight?

Answer

(b) Microwaves Microwaves travel in straight lines, so the towers must face each other.

A4.38Practice1 mark

Which cable is commonly used for cable TV connections?

Answer

(b) Coaxial cable Coaxial cable is used for cable TV.

A4.39Practice1 mark

In which topology are all the computers connected to one backbone cable?

Answer

(a) Bus In a bus topology every computer is joined to a single backbone cable.

A4.40Practice1 mark

Which topology is a combination of bus and star topologies?

Answer

(c) Tree Tree topology joins several star networks to a bus backbone.

A4.41Practice1 mark

In XML, the tags are ...

Answer

(b) created by the user HTML tags are predefined.

A4.42Practice1 mark

Which of the following is a web browser?

Answer

(b) Mozilla Firefox A browser such as Firefox, Chrome or Edge opens web pages.

A4.43Practice1 mark

The service of storing a website on a web server so that it can be opened on the Internet is called ...

Answer

(b) web hosting Web hosting keeps the website's files on a server connected to the Internet.

A4.44Practice1 mark

In packet switching, the message is ...

Answer

(b) divided into small packets The packets may take different routes.

A4.45Practice1 mark

Which topology has a hierarchical structure, with branches joined to a backbone?

Answer

(c) Tree Tree topology looks like a tree: branches (stars) joined to a backbone.

A4.46Practice1 mark

Which device is needed to connect a computer to the Internet through a telephone line?

Answer

(a) Modem A modem converts digital signals to analog (modulation) and back (demodulation).

A4.47Practice1 mark

Which card lets a computer join a wireless network?

Answer

(b) Wi-Fi card A Wi-Fi card (wireless NIC) connects a computer to a wireless network.

A4.48Practice1 mark

Which of the following is not a wired medium?

Answer

(d) Microwave Microwave is wireless; twisted pair, coaxial cable and optical fibre are wired.

A4.49Practice1 mark

Which of the following is not a protocol?

Answer

(c) Router A router is a device.

A4.50Practice1 mark

Which protocol is used for a direct connection between two nodes?

Answer

(a) PPP Point-to-Point Protocol.

A4.51Practice1 mark

Which type of network covers the largest area?

Answer

(d) WAN PAN < LAN < MAN < WAN: a WAN covers countries and continents.

A4.52Practice1 mark

The complete address of a web page typed in the browser is called its ...

Answer

(a) URL The URL is the full web address, e.g. https://www.cbse.gov.in/index.html.

A4.53Practice1 mark

Which of the following is a valid IPv4 address?

Answer

(a) 192.168.1.10 Four numbers from 0 to 255, separated by dots.

A4.54Practice1 mark

Which device connects two networks that use different protocols?

Answer

(c) Gateway A gateway translates between networks that use different protocols.

A4.55Practice1 mark

Expand HTML.

Answer

(a) HyperText Markup Language HTML = HyperText Markup Language, used to make web pages.

A4.56Practice1 mark

Expand SMTP.

Answer

(a) Simple Mail Transfer Protocol SMTP = Simple Mail Transfer Protocol, used to send e-mail.

A4.57Practice1 mark

Expand POP3.

Answer

(a) Post Office Protocol version 3 POP3 = Post Office Protocol version 3, used to download e-mail from the server.

A4.58Practice1 mark

Expand VoIP.

Answer

(b) Voice over Internet Protocol VoIP = Voice over Internet Protocol: voice calls over the Internet.

A4.59Practice1 mark

Expand NSFNET.

Answer

(a) National Science Foundation Network NSFNET = National Science Foundation Network, which later became a part of the Internet backbone.

A4.60Practice1 mark

Which of the following is a domain name?

Answer

(a) cbse.gov.in cbse.gov.in is a domain name; .in is the country domain and .gov shows a government site.

A4.61Practice1 mark

Which of the following is a web server?

Answer

(a) Apache The other three are web browsers.

A4.62Practice1 mark

Kbps stands for ...

Answer

(b) kilobits per second Kbps = kilobits per second, a unit of data rate.

A4.63Practice1 mark

Six computers are connected to one switch in star topology. How many cables go to the switch?

Answer

(c) 6 Every computer has its own cable.

A4.64Practice1 mark

Which switching technique is used on the Internet?

Answer

(b) Packet switching In packet switching, data is broken into packets that travel separately and are joined at the destination.

A5Assertion and Reason1 mark · 51 questions
A5.1SQP 2026-271 mark

Assertion (A): Opening a file in mode rb lets you read a binary file without changing it.

Reason (R): In rb mode, Python creates a new empty file if the file does not exist.

Answer

(c) A is true but R is false. Read modes give an error when the file is missing.

A5.2SQP 2026-271 mark

Assertion (A): SELECT Student_Name FROM Student WHERE Guardian_Phone IS NULL; is a valid query.

Reason (R): The = operator can be used to test for NULL.

Answer

(c) A is true but R is false. NULL is tested only with IS NULL / IS NOT NULL.

A5.3CBSE 20261 mark

Assertion (A): The expression [1, 2, 3] + '123' is invalid.

Reason (R): A list cannot be concatenated with a string.

Answer

(a) Both A and R are true and R is the correct explanation of A. The + operator needs both operands to be lists.

A5.4CBSE 20261 mark

Assertion (A): A primary key column cannot hold duplicate or NULL values.

Reason (R): A candidate key is not eligible to become the primary key.

Answer

(c) A is true but R is false. The primary key is chosen from the candidate keys.

A5.5CBSE 20251 mark

Assertion (A): For a binary file opened in rb mode, pickle.dump() gives an error.

Reason (R): pickle.dump() is used to read from a binary file.

Answer

(c) A is true but R is false. dump() writes; load() reads. Writing is not allowed in rb mode.

A5.6CBSE 20251 mark

Assertion (A): Records can be fetched from more than one table in a single SELECT query.

Reason (R): A foreign key links the rows of one table with the rows of another.

Answer

(a) Both A and R are true and R is the correct explanation of A. The join condition uses the common (foreign key) column.

A5.7Practice1 mark

Assertion (A): A Python function can return more than one value.

Reason (R): Multiple values are returned in the form of a tuple.

Answer

(a) Both A and R are true and R is the correct explanation of A. return a, b sends back the tuple (a, b).

A5.8Practice1 mark

Assertion (A): Opening an existing file in w mode erases its old contents.

Reason (R): In w mode the file pointer is placed at the end of the existing data.

Answer

(c) A is true but R is false. That is a (append) mode. w starts with an empty file.

A5.9Practice1 mark

Assertion (A): In a stack, the element inserted last is removed first.

Reason (R): A stack follows LIFO; insertion and deletion both happen at the top.

Answer

(a) Both A and R are true and R is the correct explanation of A. LIFO with both operations at the top (R) is exactly why the last element in is the first out (A).

A5.10Practice1 mark

Assertion (A): DELETE FROM student; removes the table structure from the database.

Reason (R): DELETE is a DML command.

Answer

(d) A is false but R is true. DELETE removes rows only. DROP TABLE removes the structure.

A5.11Practice1 mark

Assertion (A): A switch is more efficient than a hub.

Reason (R): A switch sends data only to the destination device, while a hub sends it to all devices.

Answer

(a) Both A and R are true and R is the correct explanation of A. The switch sends data only to the destination (R), so less traffic is wasted (A).

A5.12Practice1 mark

Assertion (A): COUNT(*) and COUNT(Phone) can give different answers for the same table.

Reason (R): COUNT(column) ignores NULL values.

Answer

(a) Both A and R are true and R is the correct explanation of A. COUNT(Phone) skips NULLs (R), while COUNT(*) counts every row, so they can differ (A).

A5.13Practice1 mark

Assertion (A): A tuple can be used as a key of a dictionary.

Reason (R): A tuple is immutable.

Answer

(a) Both A and R are true and R is the correct explanation of A. Keys must be immutable; a tuple is immutable (R), so it can be a key (A).

A5.14Practice1 mark

Assertion (A): L = [1, 2, 3] followed by L[0] = 9 is valid.

Reason (R): Lists are mutable.

Answer

(a) Both A and R are true and R is the correct explanation of A. Lists are mutable (R), so an element can be changed (A).

A5.15Practice1 mark

Assertion (A): s = "abc" followed by s[0] = "x" gives an error.

Reason (R): Strings are immutable.

Answer

(a) Both A and R are true and R is the correct explanation of A. Strings are immutable (R), so changing a character gives TypeError (A).

A5.16Practice1 mark

Assertion (A): A default parameter must be written after the non-default parameters.

Reason (R): Python matches positional arguments from left to right.

Answer

(a) Both A and R are true and R is the correct explanation of A. Arguments are matched from the left (R), so default parameters must come last (A).

A5.17Practice1 mark

Assertion (A): A local variable can be used outside its function.

Reason (R): A local variable is created when the function is called.

Answer

(d) A is false but R is true. A local variable exists only inside its function.

A5.18Practice1 mark

Assertion (A): The statement global x inside a function lets the function change the global x.

Reason (R): Without global, assigning to x inside a function creates a new local variable.

Answer

(a) Both A and R are true and R is the correct explanation of A. Without global, x = ... would create a local x (R); global makes the function use the global x (A).

A5.19Practice1 mark

Assertion (A): The finally block runs only when an exception occurs.

Reason (R): finally is used for clean-up work such as closing a file.

Answer

(d) A is false but R is true. finally runs in every case.

A5.20Practice1 mark

Assertion (A): 10 / 0 raises ZeroDivisionError.

Reason (R): Division by zero is not defined.

Answer

(a) Both A and R are true and R is the correct explanation of A. Division by zero is not defined (R), so Python raises ZeroDivisionError (A).

A5.21Practice1 mark

Assertion (A): The else block of a try statement runs when no exception occurs.

Reason (R): The else block must be written before the except block.

Answer

(c) A is true but R is false. else comes after all the except blocks.

A5.22Practice1 mark

Assertion (A): A file opened in r mode must already exist.

Reason (R): r mode creates a new file when the file is missing.

Answer

(c) A is true but R is false. It raises FileNotFoundError.

A5.23Practice1 mark

Assertion (A): readlines() returns a list.

Reason (R): read() returns the whole file as one string.

Answer

(b) Both A and R are true but R is not the correct explanation of A. Both statements are true but they are about two different methods.

A5.24Practice1 mark

Assertion (A): The pickle module is needed to store a list in a binary file.

Reason (R): pickle converts Python objects into a stream of bytes.

Answer

(a) Both A and R are true and R is the correct explanation of A. pickle turns the list into bytes (R), which can be written to a binary file (A).

A5.25Practice1 mark

Assertion (A): pickle.load() is written inside try-except while reading all the records.

Reason (R): load() raises EOFError when no record is left.

Answer

(a) Both A and R are true and R is the correct explanation of A. load() raises EOFError after the last record (R), so try-except stops the loop safely (A).

A5.26Practice1 mark

Assertion (A): Numbers read from a CSV file with csv.reader are strings.

Reason (R): csv.reader returns every row as a list of strings.

Answer

(a) Both A and R are true and R is the correct explanation of A. csv.reader gives each row as a list of strings (R), so numbers come as text (A); use int() to convert.

A5.27Practice1 mark

Assertion (A): f.tell() changes the position of the file pointer.

Reason (R): f.seek() moves the file pointer.

Answer

(d) A is false but R is true. tell() only reports the position.

A5.28Practice1 mark

Assertion (A): A stack can be made with a Python list.

Reason (R): append() and pop() add and remove at the same end of a list.

Answer

(a) Both A and R are true and R is the correct explanation of A. append() and pop() work at the same end (R), which is how a stack works (A).

A5.29Practice1 mark

Assertion (A): Popping from an empty stack is called overflow.

Reason (R): A stack follows LIFO.

Answer

(d) A is false but R is true. It is called underflow.

A5.30Practice1 mark

Assertion (A): A table can have many candidate keys.

Reason (R): A table can have only one primary key.

Answer

(b) Both A and R are true but R is not the correct explanation of A. Both are true, but R is not the reason for A.

A5.31Practice1 mark

Assertion (A): A foreign key column can have repeated values.

Reason (R): A foreign key refers to the primary key of another table.

Answer

(b) Both A and R are true but R is not the correct explanation of A. Both are true, but R only says what a foreign key refers to; it does not explain why repeats are allowed (many rows may refer to the same key).

A5.32Practice1 mark

Assertion (A): SELECT city, COUNT(*) FROM s GROUP BY city HAVING COUNT(*) > 2; is a valid query.

Reason (R): HAVING puts a condition on the groups made by GROUP BY.

Answer

(a) Both A and R are true and R is the correct explanation of A. HAVING puts a condition on groups (R), so it is correctly used after GROUP BY (A).

A5.33Practice1 mark

Assertion (A): DROP TABLE is a DML command.

Reason (R): DROP TABLE removes the table with its structure.

Answer

(d) A is false but R is true. DROP is a DDL command.

A5.34Practice1 mark

Assertion (A): SELECT DISTINCT city FROM student; shows every city only once.

Reason (R): DISTINCT removes duplicate values from the output.

Answer

(a) Both A and R are true and R is the correct explanation of A. DISTINCT removes duplicates (R), so each city appears once (A).

A5.35Practice1 mark

Assertion (A): ORDER BY marks shows the highest marks first.

Reason (R): The default order of ORDER BY is ascending.

Answer

(d) A is false but R is true. A is false: ascending is the default (R is true), so the lowest marks come first.

A5.36Practice1 mark

Assertion (A): LIKE 'A%' matches both "Aman" and "A".

Reason (R): % stands for zero or more characters.

Answer

(a) Both A and R are true and R is the correct explanation of A. % means zero or more characters (R), so 'A' alone also matches (A).

A5.37Practice1 mark

Assertion (A): commit() is needed after an INSERT query run from Python.

Reason (R): Changes are not saved permanently until commit() is called.

Answer

(a) Both A and R are true and R is the correct explanation of A. Changes are saved only after commit() (R), so INSERT needs it (A).

A5.38Practice1 mark

Assertion (A): commit() is needed after a SELECT query run from Python.

Reason (R): A SELECT query does not change the data.

Answer

(d) A is false but R is true. A is false: SELECT only reads data (R is true), so nothing needs to be saved.

A5.39Practice1 mark

Assertion (A): Optical fibre is not affected by electrical interference.

Reason (R): Optical fibre carries data in the form of light.

Answer

(a) Both A and R are true and R is the correct explanation of A. It carries light, not electricity (R), so electrical noise does not affect it (A).

A5.40Practice1 mark

Assertion (A): A hub is called an intelligent device.

Reason (R): A hub sends the data to all the connected devices.

Answer

(d) A is false but R is true. A switch is the intelligent device.

A5.41Practice1 mark

Assertion (A): In star topology, a fault in one computer's cable does not affect the other computers.

Reason (R): Every computer has its own cable to the central device.

Answer

(a) Both A and R are true and R is the correct explanation of A. Every computer has its own cable to the centre (R), so one bad cable affects only that computer (A).

A5.42Practice1 mark

Assertion (A): HTTPS is safer than HTTP.

Reason (R): HTTPS encrypts the data sent between the browser and the server.

Answer

(a) Both A and R are true and R is the correct explanation of A. HTTPS encrypts the data (R), so others cannot read it (A).

A5.43Practice1 mark

Assertion (A): SELECT * FROM A, B; gives the Cartesian product of the two tables.

Reason (R): No join condition is given in the query.

Answer

(a) Both A and R are true and R is the correct explanation of A. With no join condition (R), every row of A is paired with every row of B (A).

A5.44Practice1 mark

Assertion (A): COUNT(*) also counts the rows that have NULL values.

Reason (R): COUNT(*) counts all the rows of the table.

Answer

(a) Both A and R are true and R is the correct explanation of A. COUNT(*) counts all the rows (R), whatever the values are (A).

A5.45Practice1 mark

Assertion (A): UPDATE student SET marks = 0; changes every row of the table.

Reason (R): The query has no WHERE clause.

Answer

(a) Both A and R are true and R is the correct explanation of A. There is no WHERE clause (R), so every row is changed (A).

A5.46Practice1 mark

Assertion (A): A primary key column can hold NULL.

Reason (R): A primary key identifies every row uniquely.

Answer

(d) A is false but R is true. A primary key is never NULL.

A5.47Practice1 mark

Assertion (A): WHERE name LIKE '_a%' selects the name "Ravi".

Reason (R): In a LIKE pattern, _ stands for exactly one character.

Answer

(a) Both A and R are true and R is the correct explanation of A. _ is exactly one character (R): 'R', then 'a' in second place, then anything: "Ravi" matches (A).

A5.48Practice1 mark

Assertion (A): ALTER TABLE is a DDL command.

Reason (R): ALTER TABLE changes the structure of a table.

Answer

(a) Both A and R are true and R is the correct explanation of A. It changes the structure of a table (R), which is what DDL commands do (A).

A5.49Practice1 mark

Assertion (A): After cur.execute("DELETE FROM student WHERE rno = 5"), con.commit() must be called.

Reason (R): commit() saves the changes permanently in the database.

Answer

(a) Both A and R are true and R is the correct explanation of A. commit() saves the change permanently (R); without it the delete is not saved (A).

A5.50Practice1 mark

Assertion (A): SELECT DISTINCT city FROM s; can return fewer rows than SELECT city FROM s;.

Reason (R): DISTINCT removes the duplicate values from the output.

Answer

(a) Both A and R are true and R is the correct explanation of A. DISTINCT removes repeated cities (R), so the result can have fewer rows (A).

A5.51Practice1 mark

Assertion (A): WHERE marks BETWEEN 10 AND 20 selects the rows with marks 10 and marks 20 also.

Reason (R): BETWEEN includes both of its limits.

Answer

(a) Both A and R are true and R is the correct explanation of A. BETWEEN includes both limits (R), so 10 and 20 are selected (A).

Section B · 2 marks each

B1Explain or differentiate2 marks · 52 questions
B1.1SQP 2026-272 marks

Explain global and local variables with an example.

Answer

A global variable is created outside all functions and can be used anywhere in the program. A local variable is created inside a function and can be used only inside that function.

x = 10            # global
def demo():
    y = 5         # local
    print(x, y)
demo()
B1.2SQP 2026-272 marks

Differentiate between seek() and tell().

Answer

tell() returns the current position of the file pointer (in bytes from the start). seek(n) moves the file pointer to position n.

f = open("a.txt", "r")
f.seek(5)         # jump to the 6th byte
print(f.tell())   # 5
B1.3SQP 2026-272 marks

Differentiate between ALTER and UPDATE with an example of each.

Answer

ALTER is a DDL command; it changes the structure of a table. UPDATE is a DML command; it changes the data stored in rows.

ALTER TABLE student ADD city VARCHAR(20);
UPDATE student SET city = 'Delhi' WHERE rno = 5;
B1.4CBSE 20262 marks

Differentiate between default and positional parameters. Write a function header that uses both.

Answer

A positional parameter has no preset value, so its argument must be passed, in order. A default parameter has a value in the header and can be skipped in the call.

def calculate(a, b=5):     # a positional, b default
    return a * b
B1.5CBSE 20252 marks

What is the role of the return statement in a function? Give an example.

Answer

return sends a value back to the place where the function was called and ends the function.

def add(a, b):
    return a + b
s = add(4, 6)     # s gets 10
B1.6CBSE 20252 marks

Give one example each of:

  1. A syntax error and
  2. Implicit type conversion.
Answer

(i) A syntax error breaks the rules of the language, for example a missing colon. (ii) In implicit conversion Python changes the type by itself: int + float gives float.

def add(a, b)        # syntax error: colon missing

x = 5 + 2.5          # 7.5, int changed to float automatically
B1.7Practice2 marks

Differentiate between a text file and a binary file.

Answer

A text file stores data as readable characters, each line ends with a newline (EOL) character, and it can be opened in Notepad. A binary file stores data in the same form as in memory (bytes), has no EOL translation, is faster to read, and is not human-readable.

B1.8Practice2 marks

Differentiate between read() and readlines().

Answer

read() returns the whole file as one string. readlines() returns a list of strings, one for each line.

B1.9Practice2 marks

Differentiate between the file modes w and a.

Answer

w (write) erases the old contents and writes from the beginning. a (append) keeps the old contents and adds new data at the end. Both create the file if it does not exist.

B1.10Practice2 marks

Differentiate between an argument and a parameter.

Answer

A parameter (formal parameter) is the name written in the function header. An argument (actual parameter) is the value passed in the function call.

def area(r):          # r is a parameter
    return 3.14 * r * r
print(area(7))        # 7 is an argument
B1.11Practice2 marks

Differentiate between DELETE and DROP.

Answer

DELETE is a DML command that removes rows; the table and its structure remain. DROP is a DDL command that removes the whole table with its structure.

DELETE FROM student WHERE marks < 33;
DROP TABLE student;
B1.12Practice2 marks

Differentiate between the WHERE and HAVING clauses.

Answer

WHERE puts a condition on individual rows, before grouping. HAVING puts a condition on groups and is used with GROUP BY; it can use aggregate functions.

SELECT city, COUNT(*) FROM student
WHERE marks > 40
GROUP BY city HAVING COUNT(*) > 5;
B1.13Practice2 marks

Differentiate between mutable and immutable data types with one example of each.

Answer

A mutable object can be changed in place, e.g. a list: L[0] = 5 works. An immutable object cannot be changed after it is created, e.g. a string or a tuple: s[0] = 'x' gives an error.

B1.14Practice2 marks

Differentiate between a list and a tuple.

Answer

A list is written in [ ] and is mutable. A tuple is written in ( ) and is immutable, so it has no append() or remove().

B1.15Practice2 marks

Differentiate between == and is.

Answer

== checks whether two objects have the same value. is checks whether two names refer to the same object in memory.

B1.16Practice2 marks

Differentiate between break and continue.

Answer

break ends the loop at once. continue skips the remaining statements of the current round and goes to the next round of the loop.

B1.17Practice2 marks

Differentiate between / and //.

Answer

/ is true division and always gives a float: 7 / 2 is 3.5. // is floor division and gives the whole-number part: 7 // 2 is 3.

B1.18Practice2 marks

Differentiate between append() and extend().

Answer

append(x) adds x as one element at the end. extend(L2) adds every element of L2 at the end. [1, 2].append([3, 4]) gives [1, 2, [3, 4]]; extend gives [1, 2, 3, 4].

B1.19Practice2 marks

Differentiate between pop() and remove() of a list.

Answer

pop(i) removes the element at index i and returns it; without an index it removes the last element. remove(x) removes the first element whose value is x and returns nothing.

B1.20Practice2 marks

Differentiate between sort() and sorted().

Answer

L.sort() arranges the list L itself and returns None. sorted(L) returns a new sorted list and leaves L unchanged.

B1.21Practice2 marks

Differentiate between find() and index() of a string.

Answer

Both return the position of a substring. When the substring is not found, find() returns -1 but index() raises ValueError.

B1.22Practice2 marks

Differentiate between a syntax error and a run-time error.

Answer

A syntax error breaks a rule of the language (missing colon); the program does not start. A run-time error happens while the program is running (division by zero); the program stops in the middle.

B1.23Practice2 marks

Differentiate between a built-in function and a user-defined function.

Answer

A built-in function is already available in Python, e.g. len(), print(). A user-defined function is written by the programmer with the def keyword.

B1.24Practice2 marks

Differentiate between a keyword and an identifier.

Answer

A keyword is a reserved word with a fixed meaning, e.g. if, def. An identifier is a name given by the programmer to a variable or function, e.g. marks.

B1.25Practice2 marks

Differentiate between positional and keyword arguments.

Answer

Positional arguments are matched by their order: area(4, 5). Keyword arguments are matched by name, so the order does not matter: area(b=5, l=4).

B1.26Practice2 marks

What is the scope of a variable? Name the two types of scope.

Answer

The scope is the part of the program in which a variable can be used. Local scope: inside the function where the variable is created. Global scope: the whole program.

B1.27Practice2 marks

What is the use of the try and except blocks?

Answer

The statements that may cause an error are kept in the try block. If an error occurs, Python jumps to the matching except block, so the program does not crash.

B1.28Practice2 marks

What is the use of the finally block?

Answer

The finally block is written after try-except. It always runs, whether an exception occurs or not. It is used for clean-up work such as closing a file.

B1.29Practice2 marks

Differentiate between the file modes r+ and w+.

Answer

Both allow reading and writing. r+ needs the file to exist and keeps the old data. w+ creates the file if needed and erases the old data.

B1.30Practice2 marks

Differentiate between readline() and readlines().

Answer

readline() reads one line and returns it as a string. readlines() reads all the lines and returns them as a list of strings.

B1.31Practice2 marks

Differentiate between write() and writelines().

Answer

write(s) writes one string. writelines(L) writes all the strings of a list. Neither adds a newline by itself.

B1.32Practice2 marks

Differentiate between dump() and load() of the pickle module.

Answer

pickle.dump(obj, f) writes a Python object to a binary file. pickle.load(f) reads one object back from the binary file.

B1.33Practice2 marks

Why should a file be closed? What is the advantage of the with statement?

Answer

Closing a file saves the data from the buffer to the disk and frees the file. With with open(...) as f: the file is closed automatically, even if an error occurs.

B1.34Practice2 marks

Differentiate between a relative path and an absolute path.

Answer

An absolute path gives the full address from the drive, e.g. C:\School\data.txt. A relative path starts from the current folder, e.g. data.txt.

B1.35Practice2 marks

What is a CSV file? Write two advantages.

Answer

A CSV (Comma Separated Values) file is a text file in which each line is a record and the values are separated by commas. It is small and simple, and it opens in spreadsheet programs such as Excel.

B1.36Practice2 marks

Differentiate between writerow() and writerows().

Answer

writerow(L) writes one record (one list). writerows(LL) writes many records at once (a list of lists).

B1.37Practice2 marks

What is a stack? Write two uses of a stack.

Answer

A stack is a linear data structure in which items are added and removed at the same end, the top (LIFO). Uses: undo in an editor, back button of a browser, reversing a string.

B1.38Practice2 marks

Differentiate between overflow and underflow in a stack.

Answer

Overflow: trying to push an item into a stack that is full. Underflow: trying to pop an item from a stack that is empty.

B1.39Practice2 marks

Differentiate between a primary key and a foreign key.

Answer

A primary key identifies each row of its own table uniquely and cannot be NULL. A foreign key is a column that refers to the primary key of another table; it can repeat.

B1.40Practice2 marks

Differentiate between degree and cardinality with an example.

Answer

Degree is the number of columns and cardinality is the number of rows. A table with 5 columns and 20 rows has degree 5 and cardinality 20.

B1.41Practice2 marks

Differentiate between CHAR and VARCHAR.

Answer

CHAR(n) has a fixed length: it always uses n characters. VARCHAR(n) has a variable length: it uses only as many characters as the value has, up to n.

B1.42Practice2 marks

Differentiate between fetchone() and fetchall().

Answer

fetchone() returns the next one row as a tuple (None when no row is left). fetchall() returns all the remaining rows as a list of tuples.

B1.43Practice2 marks

What is a default parameter? Give an example.

Answer

A default parameter is a parameter that has a value in the function header. If the call does not pass a value, the default is used. In def area(l, b=5): the parameter b is a default parameter, so area(4) uses b = 5.

B1.44Practice2 marks

Differentiate between a function definition and a function call.

Answer

The definition starts with def and contains the statements of the function: def add(a, b):. The call is the statement that runs the function: add(4, 6). A function does nothing until it is called.

B1.45Practice2 marks

Differentiate between the file modes r and rb.

Answer

r opens a text file for reading; data is read as strings. rb opens a binary file for reading; data is read as bytes, for example with pickle.load().

B1.46Practice2 marks

Differentiate between the file modes a and a+.

Answer

Both add new data at the end and keep the old data. a allows only writing. a+ allows writing and reading.

B1.47Practice2 marks

Differentiate between print() and return inside a function.

Answer

print() only shows a value on the screen. return sends the value back to the calling statement, so it can be stored in a variable and used again; it also ends the function.

B1.48Practice2 marks

Differentiate between a list and a dictionary.

Answer

A list is an ordered collection in [ ]; its items are reached by index numbers. A dictionary is a collection of key : value pairs in { }; its values are reached by keys.

B1.49Practice2 marks

What is EOFError? When does it occur while reading a binary file?

Answer

EOFError means End Of File error. It occurs when pickle.load() is called but no more record is left in the file. It is handled with try-except to stop the reading loop.

B1.50Practice2 marks

Differentiate between the operators in and not in with an example.

Answer

in gives True when the value is present in the sequence: 3 in [1, 2, 3] is True. not in gives True when it is absent: 5 not in [1, 2, 3] is True.

B1.51Practice2 marks

Differentiate between isalpha() and isalnum().

Answer

isalpha() is True when the string has only letters: "abc".isalpha(). isalnum() is True when it has only letters and digits: "abc12".isalnum().

B1.52Practice2 marks

Differentiate between strip() and split().

Answer

strip() removes the spaces from both ends of a string and returns a string. split() breaks a string into parts and returns a list of strings.

B2Find and correct the errors2 marks · 41 questions
B2.1SQP 2026-272 marks

The program should print the list items in reverse order. Find the errors and rewrite the code.

Given code:

words = ["Class Test", "Term Exams", "Pre-board Exam", "Board Exam']
L = len(words)
for i in range(L, -1, -1)
    Print(words[i])
Answer

Four corrections: closing quote, colon after for, range(L-1, -1, -1), small print.

words = ["Class Test", "Term Exams", "Pre-board Exam", "Board Exam"]
L = len(words)
for i in range(L-1, -1, -1):
    print(words[i])

Output:

Board Exam
Pre-board Exam
Term Exams
Class Test
B2.2CBSE 20262 marks

CountVowels(s) should return the number of vowels in s. Rewrite it after removing the syntax and logical errors.

Given code:

def CountVowels(s):
    c = 0
    for ch in range(s):
        if 'aeiouAEIOU' in ch:
            c =+ 1
    return(ch)
Answer

Four corrections: loop over the string, check the character in the vowels, c += 1, return c.

def CountVowels(s):
    c = 0
    for ch in s:
        if ch in 'aeiouAEIOU':
            c += 1
    return c
print(CountVowels('Education'))

Output:

5
B2.3CBSE 20252 marks

Sum(N) should return the sum of the numbers 1 to N. Correct the code.

Given code:

def Sum(N):
    for I in range(N):
        S = S + I
    return S
print(Sum(10)
Answer

Three corrections: initialise S, range from 1 to N, closing bracket of print.

def Sum(N):
    S = 0
    for I in range(1, N + 1):
        S = S + I
    return S
print(Sum(10))

Output:

55
B2.4Practice2 marks

The function should return the factorial of n.

Given code:

def fact(n)
    f = 1
    for i in range(1, n):
        f =* i
    return f
print(fact(5))
Answer

Three corrections: colon after the header, range(1, n + 1), operator *=.

def fact(n):
    f = 1
    for i in range(1, n + 1):
        f *= i
    return f
print(fact(5))

Output:

120
B2.5Practice2 marks

The program should print Even or Odd for every number of the list.

Given code:

L = [12, 7, 9, 20]
for i in L
    if i % 2 = 0:
        print(i, "Even")
    Else:
        print(i, "Odd")
Answer

Three corrections: colon after for, == for comparison, small else.

L = [12, 7, 9, 20]
for i in L:
    if i % 2 == 0:
        print(i, "Even")
    else:
        print(i, "Odd")

Output:

12 Even
7 Odd
9 Odd
20 Even
B2.6Practice2 marks

The program should print every subject with its marks.

Given code:

D = {"Maths": 90, "CS": 95}
for k in D.keys:
    print(k, ":" D[k])
Answer

Two corrections: keys() needs brackets, comma between the items in print.

D = {"Maths": 90, "CS": 95}
for k in D.keys():
    print(k, ":", D[k])

Output:

Maths : 90
CS : 95
B2.7Practice2 marks

The function should return the largest number of a list.

Given code:

def largest(L):
    big = L[0]
    for x in L
        if x > big
            big == x
    return big
print(largest([4, 19, 7]))
Answer

Three corrections: colon after for, colon after if, = for assignment.

def largest(L):
    big = L[0]
    for x in L:
        if x > big:
            big = x
    return big
print(largest([4, 19, 7]))

Output:

19
B2.8Practice2 marks

The program should print the sum of the digits of a number entered by the user.

Given code:

n = input("Enter number: ")
s = 0
while n > 0:
    s = s + n % 10
    n = n / 10
print("Sum =", s)
Answer

Two corrections: convert the input with int(), use // so that n stays an integer.

n = int(input("Enter number: "))
s = 0
while n > 0:
    s = s + n % 10
    n = n // 10
print("Sum =", s)
B2.9Practice2 marks

The function should return True when the string is a palindrome.

Given code:

def is_palin(s):
    if s = s[::-1]:
        return true
    else
        return False
print(is_palin("madam"))
Answer

Three corrections: == for comparison, capital True, colon after else.

def is_palin(s):
    if s == s[::-1]:
        return True
    else:
        return False
print(is_palin("madam"))

Output:

True
B2.10Practice2 marks

The program should display the contents of notes.txt.

Given code:

f = open("notes.txt", r)
data = f.read
print(Data)
f.close
Answer

Four corrections: mode in quotes, read() with brackets, same variable name data, close() with brackets.

f = open("notes.txt", "r")
data = f.read()
print(data)
f.close()
B2.11Practice2 marks

The program should handle the error raised by a wrong number.

Given code:

try
    x = int("12a")
except valueError:
    print("Invalid")
finaly:
    print("Done")
Answer

Three corrections: colon after try, capital V in ValueError, spelling of finally.

try:
    x = int("12a")
except ValueError:
    print("Invalid")
finally:
    print("Done")

Output:

Invalid
Done
B2.12Practice2 marks

The code below was written for this task: Write a function total(L) that returns the sum of the elements of a list without using sum(). It has three errors. Find them and rewrite the correct code.

Given code:

def total(L)
    s = 0
    for x in L:
        s =+ x
    return s

print(total([4, 8, 15])
Answer

Three corrections: (1) close the bracket of the last print(; (2) put the colon at the end of def total(L):; (3) the operator is +=, not =+.

def total(L):
    s = 0
    for x in L:
        s += x
    return s

print(total([4, 8, 15]))

Output:

27
B2.13Practice2 marks

The code below was written for this task: Write a function count_vowels(s) that returns the number of vowels in a string. It has three errors. Find them and rewrite the correct code.

Given code:

def count_vowels(s)
    c = 0
    for ch in s:
        if ch in "aeiouAEIOU':
            c =+ 1
    return c

print(count_vowels("Computer Science"))
Answer

Three corrections: (1) a string must end with the same quote mark it starts with; (2) the operator is +=, not =+; (3) put the colon at the end of def count_vowels(s):.

def count_vowels(s):
    c = 0
    for ch in s:
        if ch in "aeiouAEIOU":
            c += 1
    return c

print(count_vowels("Computer Science"))

Output:

6
B2.14Practice2 marks

The code below was written for this task: Write a function reverse_words(s) that returns the sentence with its words in reverse order. It has three errors. Find them and rewrite the correct code.

Given code:

Def reverse_words(s)
    words = s.split()
    words.reverse()
    return " ".join(words)

print(reverse_words("Python is easy")
Answer

Three corrections: (1) close the bracket of the last print(; (2) def is written in small letters; (3) put the colon at the end of Def reverse_words(s):.

def reverse_words(s):
    words = s.split()
    words.reverse()
    return " ".join(words)

print(reverse_words("Python is easy"))

Output:

easy is Python
B2.15Practice2 marks

The code below was written for this task: Write a function evens(L) that returns a list of the even numbers of L. It has three errors. Find them and rewrite the correct code.

Given code:

def evens(L):
    new = []
    for x in L
        if x % 2 = 0:
            new.append(x)
    return new

print(evens([3, 8, 12, 5, 6])
Answer

Three corrections: (1) close the bracket of the last print(; (2) use == to compare; = is for assignment; (3) put the colon at the end of for x in L:.

def evens(L):
    new = []
    for x in L:
        if x % 2 == 0:
            new.append(x)
    return new

print(evens([3, 8, 12, 5, 6]))

Output:

[8, 12, 6]
B2.16Practice2 marks

The code below was written for this task: Write a function largest(a, b, c) that returns the largest of three numbers without using max(). It has three errors. Find them and rewrite the correct code.

Given code:

Def largest(a, b, c):
    big = a
    if b > big:
        big = b
    if c > big
        big = c
    return big

print(largest(14, 29, 8)
Answer

Three corrections: (1) close the bracket of the last print(; (2) def is written in small letters; (3) put the colon at the end of if c > big:.

def largest(a, b, c):
    big = a
    if b > big:
        big = b
    if c > big:
        big = c
    return big

print(largest(14, 29, 8))

Output:

29
B2.17Practice2 marks

The code below was written for this task: Write a function fact(n) that returns the factorial of n. It has three errors. Find them and rewrite the correct code.

Given code:

def fact(n)
    f = 1
    for i in range(1, n + 1):
        f =* i
    return f

Print(fact(6))
Answer

Three corrections: (1) print is written in small letters; (2) put the colon at the end of def fact(n):; (3) the operator is *=, not =*.

def fact(n):
    f = 1
    for i in range(1, n + 1):
        f *= i
    return f

print(fact(6))

Output:

720
B2.18Practice2 marks

The code below was written for this task: Write a function table(n) that prints the first five multiples of n on one line. It has three errors. Find them and rewrite the correct code.

Given code:

Def table(n):
    for i in range(1, 6):
        print(n * i, end=" '

table(7)
Answer

Three corrections: (1) def is written in small letters; (2) close the bracket of the last print(; (3) a string must end with the same quote mark it starts with.

def table(n):
    for i in range(1, 6):
        print(n * i, end=" ")

table(7)

Output:

7 14 21 28 35 
B2.19Practice2 marks

The code below was written for this task: Write a function count_word(s, w) that returns how many times the word w occurs in the sentence s. It has three errors. Find them and rewrite the correct code.

Given code:

def count_word(s, w):
    c = 0
    for x in s.split()
        if x == w:
            c =+ 1
    return c

print(count_word("the cat and the hat", "the")
Answer

Three corrections: (1) put the colon at the end of for x in s.split():; (2) close the bracket of the last print(; (3) the operator is +=, not =+.

def count_word(s, w):
    c = 0
    for x in s.split():
        if x == w:
            c += 1
    return c

print(count_word("the cat and the hat", "the"))

Output:

2
B2.20Practice2 marks

The code below was written for this task: Write a function swap_case(s) that changes capital letters to small and small letters to capital, without using swapcase(). It has three errors. Find them and rewrite the correct code.

Given code:

def swap_case(s)
    r = "'
    for ch in s:
        if ch.isupper():
            r += ch.lower()
        else:
            r += ch.upper()
    return r

Print(swap_case("Kendriya"))
Answer

Three corrections: (1) put the colon at the end of def swap_case(s):; (2) print is written in small letters; (3) a string must end with the same quote mark it starts with.

def swap_case(s):
    r = ""
    for ch in s:
        if ch.isupper():
            r += ch.lower()
        else:
            r += ch.upper()
    return r

print(swap_case("Kendriya"))

Output:

kENDRIYA
B2.21Practice2 marks

The code below was written for this task: Write a function second_largest(L) that returns the second largest number of a list of different numbers. It has three errors. Find them and rewrite the correct code.

Given code:

def second_largest(L)
    M = sorted(L)
    Return M[-2]

print(second_largest([14, 67, 29, 51])
Answer

Three corrections: (1) return is written in small letters; (2) close the bracket of the last print(; (3) put the colon at the end of def second_largest(L):.

def second_largest(L):
    M = sorted(L)
    return M[-2]

print(second_largest([14, 67, 29, 51]))

Output:

51
B2.22Practice2 marks

The code below was written for this task: Write a function remove_dup(L) that returns a list without repeated elements, keeping the first occurrence. It has three errors. Find them and rewrite the correct code.

Given code:

Def remove_dup(L):
    new = []
    for x in L
        if x not in new:
            new.append(x)
    return new

print(remove_dup([2, 5, 2, 8, 5])
Answer

Three corrections: (1) def is written in small letters; (2) close the bracket of the last print(; (3) put the colon at the end of for x in L:.

def remove_dup(L):
    new = []
    for x in L:
        if x not in new:
            new.append(x)
    return new

print(remove_dup([2, 5, 2, 8, 5]))

Output:

[2, 5, 8]
B2.23Practice2 marks

The code below was written for this task: Write a function sum_digits(n) that returns the sum of the digits of a number. It has three errors. Find them and rewrite the correct code.

Given code:

def sum_digits(n):
    s = 0
    while n > 0
        s =+ n % 10
        n //= 10
    return s

print(sum_digits(4725)
Answer

Three corrections: (1) close the bracket of the last print(; (2) put the colon at the end of while n > 0:; (3) the operator is +=, not =+.

def sum_digits(n):
    s = 0
    while n > 0:
        s += n % 10
        n //= 10
    return s

print(sum_digits(4725))

Output:

18
B2.24Practice2 marks

The code below was written for this task: Write a function fib(n) that prints the first n numbers of the Fibonacci series. It has three errors. Find them and rewrite the correct code.

Given code:

def fib(n):
    a, b = 0, 1
    for i in range(n)
        print(a, end=" '
        a, b = b, a + b

fib(7)
Answer

Three corrections: (1) put the colon at the end of for i in range(n):; (2) close the bracket of the last print(; (3) a string must end with the same quote mark it starts with.

def fib(n):
    a, b = 0, 1
    for i in range(n):
        print(a, end=" ")
        a, b = b, a + b

fib(7)

Output:

0 1 1 2 3 5 8 
B2.25Practice2 marks

The code below was written for this task: Write a function count_range(L, lo, hi) that returns how many numbers of L lie from lo to hi (both included). It has three errors. Find them and rewrite the correct code.

Given code:

def count_range(L, lo, hi):
    c = 0
    for x in L
        if lo <= x <= hi:
            c += 1
    Return c

print(count_range([12, 45, 30, 8, 27], 10, 30)
Answer

Three corrections: (1) put the colon at the end of for x in L:; (2) close the bracket of the last print(; (3) return is written in small letters.

def count_range(L, lo, hi):
    c = 0
    for x in L:
        if lo <= x <= hi:
            c += 1
    return c

print(count_range([12, 45, 30, 8, 27], 10, 30))

Output:

3
B2.26Practice2 marks

The code below was written for this task: Write a function invert(D) that returns a new dictionary in which the keys and values of D are exchanged. It has three errors. Find them and rewrite the correct code.

Given code:

def invert(D):
    new = {}
    for k in D:
        new[D[k]] = k
    Return new

print(invert({"a': 1, "b": 2})
Answer

Three corrections: (1) return is written in small letters; (2) close the bracket of the last print(; (3) a string must end with the same quote mark it starts with.

def invert(D):
    new = {}
    for k in D:
        new[D[k]] = k
    return new

print(invert({"a": 1, "b": 2}))

Output:

{1: 'a', 2: 'b'}
B2.27Practice2 marks

The code below was written for this task: Write a function initials(name) that returns the first letters of all the words of a name in capitals. It has three errors. Find them and rewrite the correct code.

Given code:

def initials(name):
    r = "'
    for w in name.split()
        r =+ w[0].upper()
    return r

print(initials("kendriya vidyalaya sangathan"))
Answer

Three corrections: (1) put the colon at the end of for w in name.split():; (2) a string must end with the same quote mark it starts with; (3) the operator is +=, not =+.

def initials(name):
    r = ""
    for w in name.split():
        r += w[0].upper()
    return r

print(initials("kendriya vidyalaya sangathan"))

Output:

KVS
B2.28Practice2 marks

The code below was written for this task: Write a function average(T) that returns the average of the numbers of a tuple. It has three errors. Find them and rewrite the correct code.

Given code:

def average(T)
    s = 0
    for x in T:
        s += x
    Return s / len(T)

print(average((10, 20, 60))
Answer

Three corrections: (1) put the colon at the end of def average(T):; (2) return is written in small letters; (3) close the bracket of the last print(.

def average(T):
    s = 0
    for x in T:
        s += x
    return s / len(T)

print(average((10, 20, 60)))

Output:

30.0
B2.29Practice2 marks

The code below was written for this task: Write a function power(b, e) that returns b raised to e using a loop. It has three errors. Find them and rewrite the correct code.

Given code:

def power(b, e):
    p = 1
    for i in range(e)
        p =* b
    return p

Print(power(2, 10))
Answer

Three corrections: (1) the operator is *=, not =*; (2) print is written in small letters; (3) put the colon at the end of for i in range(e):.

def power(b, e):
    p = 1
    for i in range(e):
        p *= b
    return p

print(power(2, 10))

Output:

1024
B2.30Practice2 marks

The code below was written for this task: Write a function positions(L, x) that returns a list of the indexes at which x occurs in L. It has three errors. Find them and rewrite the correct code.

Given code:

def positions(L, x):
    pos = []
    for i in range(len(L))
        if L[i] = x:
            pos.append(i)
    return pos

print(positions([5, 3, 5, 9, 5], 5)
Answer

Three corrections: (1) close the bracket of the last print(; (2) use == to compare; = is for assignment; (3) put the colon at the end of for i in range(len(L)):.

def positions(L, x):
    pos = []
    for i in range(len(L)):
        if L[i] == x:
            pos.append(i)
    return pos

print(positions([5, 3, 5, 9, 5], 5))

Output:

[0, 2, 4]
B2.31Practice2 marks

The code below was written for this task: Write a function hcf(a, b) that returns the highest common factor of two numbers. It has three errors. Find them and rewrite the correct code.

Given code:

def hcf(a, b):
    h = 1
    for i in range(1, min(a, b) + 1):
        if a % i = 0 and b % i == 0:
            h = i
    return h

Print(hcf(36, 48)
Answer

Three corrections: (1) close the bracket of the last print(; (2) print is written in small letters; (3) use == to compare; = is for assignment.

def hcf(a, b):
    h = 1
    for i in range(1, min(a, b) + 1):
        if a % i == 0 and b % i == 0:
            h = i
    return h

print(hcf(36, 48))

Output:

12
B2.32Practice2 marks

The code below was written for this task: Write a function count_types(s) that returns two values: the number of letters and the number of digits in s. It has three errors. Find them and rewrite the correct code.

Given code:

def count_types(s):
    a = d = 0
    for ch in s:
        If ch.isalpha():
            a =+ 1
        elif ch.isdigit():
            d += 1
    return a, d

print(count_types("Exam2027'))
Answer

Three corrections: (1) the operator is +=, not =+; (2) a string must end with the same quote mark it starts with; (3) if is written in small letters.

def count_types(s):
    a = d = 0
    for ch in s:
        if ch.isalpha():
            a += 1
        elif ch.isdigit():
            d += 1
    return a, d

print(count_types("Exam2027"))

Output:

(4, 4)
B2.33Practice2 marks

The code below was written for this task: A dictionary D has names as keys and marks as values. Write a function above_avg(D) that returns a list of the names who scored more than the average. It has three errors. Find them and rewrite the correct code.

Given code:

Def above_avg(D)
    avg = sum(D.values()) / len(D)
    names = []
    for k in D:
        if D[k] > avg:
            names.append(k)
    return names

print(above_avg({"Asha": 90, "Ravi": 60, "Tina": 75})
Answer

Three corrections: (1) def is written in small letters; (2) close the bracket of the last print(; (3) put the colon at the end of Def above_avg(D):.

def above_avg(D):
    avg = sum(D.values()) / len(D)
    names = []
    for k in D:
        if D[k] > avg:
            names.append(k)
    return names

print(above_avg({"Asha": 90, "Ravi": 60, "Tina": 75}))

Output:

['Asha']
B2.34Practice2 marks

The code below was written for this task: Write a function shift_left(L) that moves the first element of the list to the end. It has three errors. Find them and rewrite the correct code.

Given code:

Def shift_left(L)
    x = L.pop(0)
    L.append(x)

A = [1, 2, 3, 4]
shift_left(A)
print(A
Answer

Three corrections: (1) def is written in small letters; (2) close the bracket of the last print(; (3) put the colon at the end of Def shift_left(L):.

def shift_left(L):
    x = L.pop(0)
    L.append(x)

A = [1, 2, 3, 4]
shift_left(A)
print(A)

Output:

[2, 3, 4, 1]
B2.35Practice2 marks

The code below was written for this task: Write a function to_dict(K, V) that makes a dictionary from a list of keys and a list of values. It has three errors. Find them and rewrite the correct code.

Given code:

def to_dict(K, V)
    D = {}
    for i in range(len(K)):
        D[K[i]] = V[i]
    return D

print(to_dict(["x', "y"], [10, 20])
Answer

Three corrections: (1) put the colon at the end of def to_dict(K, V):; (2) a string must end with the same quote mark it starts with; (3) close the bracket of the last print(.

def to_dict(K, V):
    D = {}
    for i in range(len(K)):
        D[K[i]] = V[i]
    return D

print(to_dict(["x", "y"], [10, 20]))

Output:

{'x': 10, 'y': 20}
B2.36Practice2 marks

The code below was written for this task: Write a function grade(m) that returns "A" for marks 75 or more, "B" for 50 or more, otherwise "C". It has three errors. Find them and rewrite the correct code.

Given code:

def grade(m):
    if m >= 75:
        Return "A'
    elif m >= 50
        return "B"
    else:
        return "C"

print(grade(82), grade(64), grade(31))
Answer

Three corrections: (1) put the colon at the end of elif m >= 50:; (2) return is written in small letters; (3) a string must end with the same quote mark it starts with.

def grade(m):
    if m >= 75:
        return "A"
    elif m >= 50:
        return "B"
    else:
        return "C"

print(grade(82), grade(64), grade(31))

Output:

A B C
B2.37Practice2 marks

The code below was written for this task: Write a function min_max(L) that returns both the smallest and the largest number of a list. It has three errors. Find them and rewrite the correct code.

Given code:

def min_max(L):
    lo = hi = L[0]
    For x in L
        if x < lo:
            lo = x
        if x > hi:
            hi = x
    return lo, hi

print(min_max([14, 3, 27, 9])
Answer

Three corrections: (1) close the bracket of the last print(; (2) put the colon at the end of for x in L:; (3) for is written in small letters.

def min_max(L):
    lo = hi = L[0]
    for x in L:
        if x < lo:
            lo = x
        if x > hi:
            hi = x
    return lo, hi

print(min_max([14, 3, 27, 9]))

Output:

(3, 27)
B2.38Practice2 marks

The code below was written for this task: Write a function interest(p, r=5, t=1) that returns the simple interest. Call it with one, two and three arguments. It has three errors. Find them and rewrite the correct code.

Given code:

Def interest(p, r=5, t=1)
    return p * r * t / 100

print(interest(1000), interest(1000, 8), interest(1000, 8, 2)
Answer

Three corrections: (1) put the colon at the end of def interest(p, r=5, t=1):; (2) close the bracket of the last print(; (3) def is written in small letters.

def interest(p, r=5, t=1):
    return p * r * t / 100

print(interest(1000), interest(1000, 8), interest(1000, 8, 2))

Output:

50.0 80.0 160.0
B2.39Practice2 marks

The code below was written for this task: Write a function squares(n) that returns a dictionary of the numbers 1 to n with their squares. It has three errors. Find them and rewrite the correct code.

Given code:

Def squares(n):
    D = {}
    for i in range(1, n + 1)
        D[i] = i * i
    return D

print(squares(4)
Answer

Three corrections: (1) put the colon at the end of for i in range(1, n + 1):; (2) def is written in small letters; (3) close the bracket of the last print(.

def squares(n):
    D = {}
    for i in range(1, n + 1):
        D[i] = i * i
    return D

print(squares(4))

Output:

{1: 1, 2: 4, 3: 9, 4: 16}
B2.40Practice2 marks

The code below was written for this task: Write a function is_leap(y) that returns True if y is a leap year. It has three errors. Find them and rewrite the correct code.

Given code:

Def is_leap(y):
    if y % 400 = 0:
        return True
    if y % 100 == 0:
        return False
    return y % 4 == 0

print(is_leap(2028), is_leap(2100), is_leap(2000)
Answer

Three corrections: (1) close the bracket of the last print(; (2) def is written in small letters; (3) use == to compare; = is for assignment.

def is_leap(y):
    if y % 400 == 0:
        return True
    if y % 100 == 0:
        return False
    return y % 4 == 0

print(is_leap(2028), is_leap(2100), is_leap(2000))

Output:

True False True
B2.41Practice2 marks

The code below was written for this task: Write a function count_long(L, n) that returns how many strings of the list L have more than n characters. It has three errors. Find them and rewrite the correct code.

Given code:

def count_long(L, n):
    c = 0
    For s in L
        if len(s) > n:
            c += 1
    return c

print(count_long(["sun", "planet", "star", "galaxy"], 4)
Answer

Three corrections: (1) for is written in small letters; (2) put the colon at the end of For s in L:; (3) close the bracket of the last print(.

def count_long(L, n):
    c = 0
    for s in L:
        if len(s) > n:
            c += 1
    return c

print(count_long(["sun", "planet", "star", "galaxy"], 4))

Output:

2
B3Write statements using built-in functions2 marks · 72 questions
B3.1SQP 2026-272 marks

Write a statement to:

  1. Check whether the string username starts with "admin"
  2. Count how many times the largest value occurs in the list data.
Answer
username.startswith("admin")
data.count(max(data))
B3.2CBSE 20262 marks

Write a statement to:

  1. Create a sorted copy L1 of list L without changing L
  2. Check whether ch is a letter or a digit.
Answer
L1 = sorted(L)
ch.isalnum()
B3.3CBSE 20262 marks

D1 is a dictionary. Write an expression to:

  1. Check whether the key 'RNo' is present
  2. Check whether any key has the value 12.
Answer
'RNo' in D1
12 in D1.values()
B3.4CBSE 20262 marks

D1 is a dictionary. Write a statement to:

  1. Add 'RNo': 12 only if the key 'RNo' is not present
  2. Delete all the elements.
Answer
D1.setdefault('RNo', 12)
D1.clear()
B3.5CBSE 20252 marks

Write a statement to:

  1. Get the value of the key "Raj" from dictionary D
  2. Find the number of elements in dictionary D1.
Answer
D.get("Raj")
len(D1)
B3.6CBSE 20252 marks

Write a statement to:

  1. Add all elements of dictionary D to D1
  2. Delete the element with key "Amit" from D1.
Answer
D1.update(D)
D1.pop("Amit")
B3.7Practice2 marks

Write a statement to:

  1. Remove the last element of list L and store it in x
  2. Add all elements of list L2 at the end of L.
Answer
x = L.pop()
L.extend(L2)
B3.8Practice2 marks

Write a statement to:

  1. Break the string s into a list of words
  2. Join the words of list W with a hyphen.
Answer
W = s.split()
"-".join(W)
B3.9Practice2 marks

Write a statement to:

  1. Find the position of the first 'a' in string s
  2. Count how many times 'a' occurs in s.
Answer
s.find('a')
s.count('a')
B3.10Practice2 marks

Write a statement to:

  1. Check whether string s contains only digits
  2. Remove the spaces from both ends of s.
Answer
s.isdigit()
s.strip()
B3.11Practice2 marks

Write a statement to:

  1. Insert 50 at index 2 of list L
  2. Remove the first occurrence of 30 from L.
Answer
L.insert(2, 50)
L.remove(30)
B3.12Practice2 marks

Write a statement to:

  1. Display the largest value of tuple T
  2. Display the keys of dictionary D in sorted order.
Answer
print(max(T))
print(sorted(D.keys()))
B3.13Practice2 marks

Write a Python statement to:

  1. Change the string s to capital letters
  2. Check whether s ends with ".py".
Answer
s.upper()
s.endswith(".py")
B3.14Practice2 marks

Write a Python statement to:

  1. Replace every "a" in s with "@"
  2. Find the number of characters in s.
Answer
s.replace("a", "@")
len(s)
B3.15Practice2 marks

Write a Python statement to:

  1. Reverse the list L in place
  2. Arrange L in descending order.
Answer
L.reverse()
L.sort(reverse=True)
B3.16Practice2 marks

Write a Python statement to:

  1. Find the index of 25 in list L
  2. Count how many times 25 occurs in L.
Answer
L.index(25)
L.count(25)
B3.17Practice2 marks

Write a Python statement to:

  1. Delete the element at index 2 of list L
  2. Remove all the elements of L.
Answer
L.pop(2)
L.clear()
B3.18Practice2 marks

Write a Python statement to:

  1. Get the last three elements of list L
  2. Get every second element of L.
Answer
L[-3:]
L[::2]
B3.19Practice2 marks

Write a Python statement to:

  1. Find the smallest element of list L
  2. Find the sum of all the elements of L.
Answer
min(L)
sum(L)
B3.20Practice2 marks

Write a Python statement to:

  1. Change the tuple T into a list
  2. Find the number of elements in T.
Answer
list(T)
len(T)
B3.21Practice2 marks

Write a Python statement to:

  1. Check whether 5 is present in tuple T
  2. Find the position of 5 in T.
Answer
5 in T
T.index(5)
B3.22Practice2 marks

Write a Python statement to:

  1. Display all the keys of dictionary D
  2. Display all the values of D.
Answer
print(D.keys())
print(D.values())
B3.23Practice2 marks

Write a Python statement to:

  1. Add the key "City" with value "Delhi" to dictionary D
  2. Remove the item that was added last.
Answer
D["City"] = "Delhi"
D.popitem()
B3.24Practice2 marks

Write a Python statement to:

  1. Get all the (key, value) pairs of dictionary D
  2. Make a copy of D named D2.
Answer
D.items()
D2 = D.copy()
B3.25Practice2 marks

Write a Python statement to:

  1. Check whether all the letters of s are small
  2. Make the first letter of every word of s capital.
Answer
s.islower()
s.title()
B3.26Practice2 marks

Write a Python statement to:

  1. Remove the spaces on the left side of s
  2. Check whether s has only letters.
Answer
s.lstrip()
s.isalpha()
B3.27Practice2 marks

Write a Python statement to:

  1. Split the string s at every comma
  2. Find the number of words in s.
Answer
s.split(",")
len(s.split())
B3.28Practice2 marks

Write a Python statement to:

  1. Generate a random integer from 1 to 6
  2. Generate a random decimal number between 0 and 1. (random is already imported.)
Answer
random.randint(1, 6)
random.random()
B3.29Practice2 marks

Write a Python statement to:

  1. Find the square root of 49
  2. Find 2 to the power 5. (math is already imported.)
Answer
math.sqrt(49)
math.pow(2, 5)
B3.30Practice2 marks

Write a Python statement to:

  1. Open the text file "data.txt" for reading as f
  2. Read its first 10 characters.
Answer
f = open("data.txt", "r")
f.read(10)
B3.31Practice2 marks

Write a Python statement to:

  1. Move the file pointer of f to the beginning
  2. Display the current position of the file pointer.
Answer
f.seek(0)
print(f.tell())
B3.32Practice2 marks

Write a Python statement to:

  1. Write the list rec into the binary file f
  2. Read one record from the binary file f.
Answer
pickle.dump(rec, f)
rec = pickle.load(f)
B3.33Practice2 marks

Write a Python statement to:

  1. Create a csv writer object w for the file f
  2. Write the row [1, "Asha"] with it.
Answer
w = csv.writer(f)
w.writerow([1, "Asha"])
B3.34Practice2 marks

Write a Python statement to:

  1. Push 25 onto the stack st
  2. Look at the top element without removing it.
Answer
st.append(25)
st[-1]
B3.35Practice2 marks

Write a Python statement to:

  1. Pop the top element of stack st into x
  2. Check whether st is empty.
Answer
x = st.pop()
len(st) == 0
B3.36Practice2 marks

Write a Python statement to:

  1. Create a cursor cur from the connection con
  2. Run the query "SELECT * FROM student".
Answer
cur = con.cursor()
cur.execute("SELECT * FROM student")
B3.37Practice2 marks

Write a Python statement to:

  1. Fetch all the rows of the last query into data
  2. Get the number of rows fetched.
Answer
data = cur.fetchall()
cur.rowcount
B3.38Practice2 marks

Write a Python statement to:

  1. Save the changes made to the database permanently
  2. Close the connection con.
Answer
con.commit()
con.close()
B3.39Practice2 marks

Write a Python statement to:

  1. Convert the string "45" to an integer
  2. Convert the integer 7 to a float.
Answer
int("45")
float(7)
B3.40Practice2 marks

Write a Python statement to:

  1. Get the first 3 characters of s
  2. Get the last character of s.
Answer
s[:3]
s[-1]
B3.41Practice2 marks

Write a Python statement to:

  1. Join the strings of list L with a space between them
  2. Repeat the string s three times.
Answer
" ".join(L)
s * 3
B3.42Practice2 marks

Write a Python statement to:

  1. Find the largest of three numbers a, b, c
  2. Find the positive value of x.
Answer
max(a, b, c)
abs(x)
B3.43Practice2 marks

Write a Python statement to:

  1. Check whether "KV" is present in the string s
  2. Check whether all the letters of s are capital.
Answer
"KV" in s
s.isupper()
B3.44Practice2 marks

Write a Python statement to:

  1. Count the spaces in the string s
  2. Find the position of the first space in s.
Answer
s.count(" ")
s.find(" ")
B3.45Practice2 marks

Write a Python statement to:

  1. Remove the spaces from the right side of s
  2. Check whether s starts with "The".
Answer
s.rstrip()
s.startswith("The")
B3.46Practice2 marks

Write a Python statement to:

  1. Get the last three characters of s
  2. Get the string s in reverse order.
Answer
s[-3:]
s[::-1]
B3.47Practice2 marks

Write a Python statement to:

  1. Make only the first letter of s capital
  2. Count the words in s.
Answer
s.capitalize()
len(s.split())
B3.48Practice2 marks

Write a Python statement to:

  1. Break s into three parts at the first "="
  2. Check whether s has only letters and digits.
Answer
s.partition("=")
s.isalnum()
B3.49Practice2 marks

Write a Python statement to:

  1. Add 99 at the beginning of list L
  2. Remove the first element of L and store it in x.
Answer
L.insert(0, 99)
x = L.pop(0)
B3.50Practice2 marks

Write a Python statement to:

  1. Find the largest element of list L
  2. Find the index of that largest element.
Answer
max(L)
L.index(max(L))
B3.51Practice2 marks

Write a Python statement to:

  1. Make a new list M with the elements of L in descending order
  2. Find the number of elements in L.
Answer
M = sorted(L, reverse=True)
len(L)
B3.52Practice2 marks

Write a Python statement to:

  1. Add all the elements of tuple T at the end of list L
  2. Check whether 10 is present in L.
Answer
L.extend(T)
10 in L
B3.53Practice2 marks

Write a Python statement to:

  1. Make a tuple of the first and the last element of list L
  2. Get the elements of L from index 1 to index 3.
Answer
(L[0], L[-1])
L[1:4]
B3.54Practice2 marks

Write a Python statement to:

  1. Change the list L into a tuple
  2. Count how many times 0 comes in tuple T.
Answer
tuple(L)
T.count(0)
B3.55Practice2 marks

Write a Python statement to:

  1. Find the total of the numbers of tuple T
  2. Find the smallest number of T.
Answer
sum(T)
min(T)
B3.56Practice2 marks

Write a Python statement to:

  1. Create an empty dictionary D
  2. Add the key 1 with the value "one" to it.
Answer
D = {}
D[1] = "one"
B3.57Practice2 marks

Write a Python statement to:

  1. Get the value of the key "Age" from D, or 0 if the key is missing
  2. Remove the key "Age" and store its value in x.
Answer
D.get("Age", 0)
x = D.pop("Age")
B3.58Practice2 marks

Write a Python statement to:

  1. Get the keys of dictionary D in sorted order
  2. Find the largest value stored in D.
Answer
sorted(D)
max(D.values())
B3.59Practice2 marks

Write a Python statement to:

  1. Make a dictionary D with the keys of list K, every value being 0
  2. Find the number of pairs in D.
Answer
D = dict.fromkeys(K, 0)
len(D)
B3.60Practice2 marks

Write a Python statement to:

  1. Check that the key "RNo" is not present in D
  2. Change the value of the key "RNo" to 15.
Answer
"RNo" not in D
D["RNo"] = 15
B3.61Practice2 marks

Write a Python statement to:

  1. Open the text file "notes.txt" as f for adding data at the end
  2. Write the line "Bye" in it.
Answer
f = open("notes.txt", "a")
f.write("Bye\n")
B3.62Practice2 marks

Write a Python statement to:

  1. Read one line from the text file f
  2. Read all the remaining lines of f into a list L.
Answer
f.readline()
L = f.readlines()
B3.63Practice2 marks

Write a Python statement to:

  1. Open the binary file "data.dat" as f for reading
  2. Close the file f.
Answer
f = open("data.dat", "rb")
f.close()
B3.64Practice2 marks

Write a Python statement to:

  1. Create a csv reader object r for the file f
  2. Skip the first (header) row.
Answer
r = csv.reader(f)
next(r)
B3.65Practice2 marks

Write a Python statement to:

  1. Open "m.csv" as f for writing so that no blank lines come between rows
  2. Write the list of rows LL in one call with the writer w.
Answer
f = open("m.csv", "w", newline="")
w.writerows(LL)
B3.66Practice2 marks

Write a Python statement to:

  1. Find the number of elements in the stack st
  2. Pop an element into x only when the stack is not empty.
Answer
len(st)
if len(st) > 0: x = st.pop()
B3.67Practice2 marks

Write a Python statement to:

  1. Round 4.3 up to the next whole number
  2. Round 4.3 down to the whole number below. (math is already imported.)
Answer
math.ceil(4.3)
math.floor(4.3)
B3.68Practice2 marks

Write a Python statement to:

  1. Find the average of the numbers of list L
  2. Find the middle value of L. (statistics is already imported.)
Answer
statistics.mean(L)
statistics.median(L)
B3.69Practice2 marks

Write a Python statement to:

  1. Generate a random integer from 10 to 20, both included
  2. Generate a random integer from 0 to 9 with randrange(). (random is already imported.)
Answer
random.randint(10, 20)
random.randrange(10)
B3.70Practice2 marks

Write a Python statement to:

  1. Change the string "3.5" into a decimal number
  2. Change the number 25 into a string.
Answer
float("3.5")
str(25)
B3.71Practice2 marks

Write a Python statement to:

  1. Check whether the number n is even
  2. Find the remainder when n is divided by 7.
Answer
n % 2 == 0
n % 7
B3.72Practice2 marks

Write a Python statement to:

  1. Change all the letters of s to small letters
  2. Replace every space of s with an underscore.
Answer
s.lower()
s.replace(" ", "_")
B4Predict the output, random module2 marks · 45 questions
B4.1SQP 2026-272 marks

Write the output of the code.

text = "Python Programming"
print(text.replace("o", "0"))
print(text.find("z"))
Answer

Output:

Pyth0n Pr0gramming
-1

Working (step by step)

LineStatementValues after this stepPrinted
1text = "Python Programming"text = 'Python Programming'
2print(text.replace("o", "0"))Pyth0n Pr0gramming⏎
3print(text.find("z"))-1⏎
B4.2SQP 2026-272 marks

Write the output of the code.

s = "gLaD5"
L = []
i = 0
while i < len(s):
    if s[i].isupper():
        L.append(s[i].lower())
    elif s[i].isdigit():
        L.append(int(s[i]) * 2)
    else:
        L.append("#")
    i += 1
print(L)
Answer

Output:

['#', 'l', '#', 'd', 10]

Working (step by step)

LineStatementValues after this stepPrinted
1s = "gLaD5"s = 'gLaD5'
2L = []L = []
3i = 0i = 0
4while i < len(s):condition is True
5if s[i].isupper():condition is False
7elif s[i].isdigit():condition is False
10L.append("#")L = ['#']
11i += 1i = 1
4while i < len(s):condition is True
5if s[i].isupper():condition is True
6L.append(s[i].lower())L = ['#', 'l']
11i += 1i = 2
4while i < len(s):condition is True
5if s[i].isupper():condition is False
7elif s[i].isdigit():condition is False
10L.append("#")L = ['#', 'l', '#']

… the same steps continue for the remaining values.

B4.3SQP 2026-272 marks

Which output is possible: (a) Sudoku@@Tic-Tac-Toe@@Puzzle@@ (b) Scrabble@@Sudoku@@Tic-Tac-Toe@@ (c) Chess@@Scrabble@@Tic-Tac-Toe@@ (d) Scrabble@@Tic-Tac-Toe@@

import random
games = {0: "Chess", 1: "Scrabble", 2: "Sudoku", 3: "Tic-Tac-Toe", 4: "Puzzle"}
start_key = random.randint(1, 2)
end_key = random.randrange(3, 4)
for k in range(start_key, end_key + 1):
    print(games[k], end="@@")
Answer

(b). start_key is 1 or 2. randrange(3, 4) can give only 3. So the loop runs from 1 or 2 up to 3, in order, without skipping. Key 0 (Chess) and key 4 (Puzzle) can never appear.

B4.4CBSE 20252 marks

Write the output of the code.

try:
    print('WORD' + '5', end='#')
except TypeError:
    print('ERROR', end='#')
finally:
    print('OVER')
Answer

Output:

WORD5#OVER

Working (step by step)

LineStatementValues after this stepPrinted
2print('WORD' + '5', end='#')WORD5#
6print('OVER')OVER⏎
B4.5Practice2 marks

Which of these can never be the output: (a) Spade#Club# (b) Club#Diamond# (c) Heart#Club# (d) Spade#Diamond#

import random
S = ["Heart", "Spade", "Club", "Diamond"]
for i in range(1, 3):
    print(S[random.randint(i, i + 1)], end="#")
Answer

(c). When i is 1 the index is 1 or 2, so the first word is Spade or Club. Index 0 (Heart) is never picked.

B4.6Practice2 marks

Write the output of the code.

def change(a, b=10):
    a = a + b
    b = a - b
    print(a, b, sep="$$")
x = 5
change(x)
print(x)
Answer

Output:

15$$5
5

Working (step by step)

LineStatementValues after this stepPrinted
5x = 5x = 5
6change(x)a = 5, b = 10
2a = a + ba = 15
3b = a - bb = 5
4print(a, b, sep="$$")x = 515$$5⏎
7print(x)5⏎
B4.7Practice2 marks

Write the output of the code.

D = {"S01": 45, "S02": 60, "S03": 38}
for k in D:
    if D[k] > 40:
        print(k, end="#")
Answer

Output:

S01#S02#

Working (step by step)

LineStatementValues after this stepPrinted
1D = {"S01": 45, "S02": 60, "S03": 38}D = {'S01': 45, 'S02': 60, 'S03': 38}
2for k in D:k = 'S01'
3if D[k] > 40:condition is True
4print(k, end="#")S01#
2for k in D:k = 'S02'
3if D[k] > 40:condition is True
4print(k, end="#")S02#
2for k in D:k = 'S03'
3if D[k] > 40:condition is False
2for k in D:loop ends (no more values)
B4.8Practice2 marks

Write the output of the code.

def add(L):
    L.append(L[0] + L[-1])
    L = [0]
A = [2, 4, 6]
add(A)
print(A)
Answer

The list A is changed by append because a list is mutable. The line L = [0] only makes a new local list.

Output:

[2, 4, 6, 8]

Working (step by step)

LineStatementValues after this stepPrinted
4A = [2, 4, 6]A = [2, 4, 6]
5add(A)L = [2, 4, 6]
2L.append(L[0] + L[-1])L = [2, 4, 6, 8]
3L = [0]A = [2, 4, 6, 8]
6print(A)[2, 4, 6, 8]⏎
B4.9Practice2 marks

Write the output of the code.

s = "Exam2027"
t = ""
for ch in s:
    if ch.isdigit():
        t = ch + t
    elif ch.isupper():
        t = t + ch.lower()
    else:
        t = t + ch.upper()
print(t)
Answer

Output:

7202eXAM

Working (step by step)

LineStatementValues after this stepPrinted
1s = "Exam2027"s = 'Exam2027'
2t = ""t = ''
3for ch in s:ch = 'E'
4if ch.isdigit():condition is False
6elif ch.isupper():condition is True
7t = t + ch.lower()t = 'e'
3for ch in s:ch = 'x'
4if ch.isdigit():condition is False
6elif ch.isupper():condition is False
9t = t + ch.upper()t = 'eX'
3for ch in s:ch = 'a'
4if ch.isdigit():condition is False
6elif ch.isupper():condition is False
9t = t + ch.upper()t = 'eXA'
3for ch in s:ch = 'm'
4if ch.isdigit():condition is False

… the same steps continue for the remaining values.

B4.10Practice2 marks

Write the output of the code.

def show(x, y=2, z=3):
    return x + y * z
print(show(1), show(1, z=1), show(y=0, x=5))
Answer

Output:

7 3 5

Working (step by step)

LineStatementValues after this stepPrinted
3print(show(1), show(1, z=1), show(y=0, x=5))x = 1, y = 2, z = 3
2return x + y * zz = 1
2return x + y * zx = 5, y = 0, z = 3
2return x + y * z7 3 5⏎
B4.11Practice2 marks

What are the smallest and largest values that a can take? Write all the possible outputs.

import random
L = [10, 20, 30, 40, 50]
a = random.randint(1, 3)
for i in range(a, 4):
    print(L[i], end=" ")
Answer

a can be 1, 2 or 3. Possible outputs: 20 30 40, 30 40, 40.

B4.12Practice2 marks

Write the output of the code.

x = 10
def f():
    global x
    x = x + 5
f()
print(x)
Answer

Output:

15

Working (step by step)

LineStatementValues after this stepPrinted
1x = 10x = 10
4x = x + 5x = 15
6print(x)15⏎
B4.13Practice2 marks

Write the output of the code.

def g(a, b=2):
    return a ** b
print(g(3), g(2, 3))
Answer

Output:

9 8

Working (step by step)

LineStatementValues after this stepPrinted
3print(g(3), g(2, 3))a = 3, b = 2
2return a ** ba = 2, b = 3
2return a ** b9 8⏎
B4.14Practice2 marks

Write the output of the code.

L = [1, 2, 3, 4, 5]
print(L[::2], L[-2:])
Answer

Output:

[1, 3, 5] [4, 5]

Working (step by step)

LineStatementValues after this stepPrinted
1L = [1, 2, 3, 4, 5]L = [1, 2, 3, 4, 5]
2print(L[::2], L[-2:])[1, 3, 5] [4, 5]⏎
B4.15Practice2 marks

Write the output of the code.

s = "KVS Delhi"
print(s.upper(), s.split()[1][0])
Answer

Output:

KVS DELHI D

Working (step by step)

LineStatementValues after this stepPrinted
1s = "KVS Delhi"s = 'KVS Delhi'
2print(s.upper(), s.split()[1][0])KVS DELHI D⏎
B4.16Practice2 marks

Write the output of the code.

D = {"a": 1, "b": 2, "c": 3}
t = 0
for k in D:
    t += D[k]
print(t, len(D))
Answer

Output:

6 3

Working (step by step)

LineStatementValues after this stepPrinted
1D = {"a": 1, "b": 2, "c": 3}D = {'a': 1, 'b': 2, 'c': 3}
2t = 0t = 0
3for k in D:k = 'a'
4t += D[k]t = 1
3for k in D:k = 'b'
4t += D[k]t = 3
3for k in D:k = 'c'
4t += D[k]t = 6
3for k in D:loop ends (no more values)
5print(t, len(D))6 3⏎
B4.17Practice2 marks

Write the output of the code.

for i in range(3):
    for j in range(i + 1):
        print("*", end="")
    print()
Answer

Output:

*
**
***

Working (step by step)

LineStatementValues after this stepPrinted
1for i in range(3):i = 0
2for j in range(i + 1):j = 0
3print("*", end="")*
2for j in range(i + 1):loop ends (no more values)
4print()⏎
1for i in range(3):i = 1
2for j in range(i + 1):loop ends (no more values)
3print("*", end="")*
2for j in range(i + 1):j = 1
3print("*", end="")*
2for j in range(i + 1):loop ends (no more values)
4print()⏎
1for i in range(3):i = 2
2for j in range(i + 1):j = 0
3print("*", end="")*
2for j in range(i + 1):j = 1

… the same steps continue for the remaining values.

B4.18Practice2 marks

Write the output of the code.

n = 4
f = 1
while n > 1:
    f *= n
    n -= 1
print(f)
Answer

Output:

24

Working (step by step)

LineStatementValues after this stepPrinted
1n = 4n = 4
2f = 1f = 1
3while n > 1:condition is True
4f *= nf = 4
5n -= 1n = 3
3while n > 1:condition is True
4f *= nf = 12
5n -= 1n = 2
3while n > 1:condition is True
4f *= nf = 24
5n -= 1n = 1
3while n > 1:condition is False
6print(f)24⏎
B4.19Practice2 marks

Write the output of the code.

L = [3, 6, 9]
for i in range(len(L)):
    L[i] = L[i] // 3
print(L)
Answer

Output:

[1, 2, 3]

Working (step by step)

LineStatementValues after this stepPrinted
1L = [3, 6, 9]L = [3, 6, 9]
2for i in range(len(L)):i = 0
3L[i] = L[i] // 3L = [1, 6, 9]
2for i in range(len(L)):i = 1
3L[i] = L[i] // 3L = [1, 2, 9]
2for i in range(len(L)):i = 2
3L[i] = L[i] // 3L = [1, 2, 3]
2for i in range(len(L)):loop ends (no more values)
4print(L)[1, 2, 3]⏎
B4.20Practice2 marks

Write the output of the code.

def swap(a, b):
    a, b = b, a
    return a, b
p, q = swap(4, 7)
print(p, q)
Answer

Output:

7 4

Working (step by step)

LineStatementValues after this stepPrinted
4p, q = swap(4, 7)a = 4, b = 7
2a, b = b, aa = 7, b = 4
3return a, bp = 7, q = 4
5print(p, q)7 4⏎
B4.21Practice2 marks

Write the output of the code.

t = (1, 2, 3)
a, b, c = t
print(a + c, b * 2)
Answer

Output:

4 4

Working (step by step)

LineStatementValues after this stepPrinted
1t = (1, 2, 3)t = (1, 2, 3)
2a, b, c = ta = 1, b = 2, c = 3
3print(a + c, b * 2)4 4⏎
B4.22Practice2 marks

Write the output of the code.

s = "abcdef"
r = ""
for ch in s:
    if ch in "aeiou":
        r += ch.upper()
    else:
        r += "*"
print(r)
Answer

Output:

A***E*

Working (step by step)

LineStatementValues after this stepPrinted
1s = "abcdef"s = 'abcdef'
2r = ""r = ''
3for ch in s:ch = 'a'
4if ch in "aeiou":condition is True
5r += ch.upper()r = 'A'
3for ch in s:ch = 'b'
4if ch in "aeiou":condition is False
7r += "*"r = 'A*'
3for ch in s:ch = 'c'
4if ch in "aeiou":condition is False
7r += "*"r = 'A**'
3for ch in s:ch = 'd'
4if ch in "aeiou":condition is False
7r += "*"r = 'A***'
3for ch in s:ch = 'e'
4if ch in "aeiou":condition is True

… the same steps continue for the remaining values.

B4.23Practice2 marks

Write the output of the code.

try:
    n = int("25")
    print(n // 0)
except ZeroDivisionError:
    print("Zero")
else:
    print("OK")
finally:
    print("End")
Answer

Output:

Zero
End

Working (step by step)

LineStatementValues after this stepPrinted
2n = int("25")n = 25
5print("Zero")Zero⏎
9print("End")End⏎
B4.24Practice2 marks

Write the output of the code.

try:
    L = [1, 2]
    print(L[2])
except IndexError:
    print("No such index")
Answer

Output:

No such index

Working (step by step)

LineStatementValues after this stepPrinted
2L = [1, 2]L = [1, 2]
5print("No such index")No such index⏎
B4.25Practice2 marks

Write the output of the code.

def count(L):
    c = 0
    for x in L:
        if x % 2 == 0:
            c += 1
    return c
print(count([2, 5, 8, 11, 14]))
Answer

Output:

3

Working (step by step)

LineStatementValues after this stepPrinted
7print(count([2, 5, 8, 11, 14]))L = [2, 5, 8, 11, 14]
2c = 0c = 0
3for x in L:x = 2
4if x % 2 == 0:condition is True
5c += 1c = 1
3for x in L:x = 5
4if x % 2 == 0:condition is False
3for x in L:x = 8
4if x % 2 == 0:condition is True
5c += 1c = 2
3for x in L:x = 11
4if x % 2 == 0:condition is False
3for x in L:x = 14
4if x % 2 == 0:condition is True
5c += 1c = 3
3for x in L:loop ends (no more values)
6return c3⏎
B4.26Practice2 marks

Write the output of the code.

x = 5
def show():
    x = 9
    print(x, end=" ")
show()
print(x)
Answer

Output:

9 5

Working (step by step)

LineStatementValues after this stepPrinted
1x = 5x = 5
3x = 9x = 9
4print(x, end=" ")x = 59
6print(x)5⏎
B4.27Practice2 marks

Write the output of the code.

L = ["a", "b"]
M = L
M.append("c")
print(L, len(M))
Answer

Output:

['a', 'b', 'c'] 3

Working (step by step)

LineStatementValues after this stepPrinted
1L = ["a", "b"]L = ['a', 'b']
2M = LM = ['a', 'b']
3M.append("c")L = ['a', 'b', 'c'], M = ['a', 'b', 'c']
4print(L, len(M))['a', 'b', 'c'] 3⏎
B4.28Practice2 marks

Write the output of the code.

D = {}
for w in ["red", "blue", "red"]:
    D[w] = D.get(w, 0) + 1
print(D)
Answer

Output:

{'red': 2, 'blue': 1}

Working (step by step)

LineStatementValues after this stepPrinted
1D = {}D = {}
2for w in ["red", "blue", "red"]:w = 'red'
3D[w] = D.get(w, 0) + 1D = {'red': 1}
2for w in ["red", "blue", "red"]:w = 'blue'
3D[w] = D.get(w, 0) + 1D = {'red': 1, 'blue': 1}
2for w in ["red", "blue", "red"]:w = 'red'
3D[w] = D.get(w, 0) + 1D = {'red': 2, 'blue': 1}
2for w in ["red", "blue", "red"]:loop ends (no more values)
4print(D){'red': 2, 'blue': 1}⏎
B4.29Practice2 marks

Write the output of the code.

s = "Python"
print(s[0] + s[-1], s.replace("P", "J"))
Answer

Output:

Pn Jython

Working (step by step)

LineStatementValues after this stepPrinted
1s = "Python"s = 'Python'
2print(s[0] + s[-1], s.replace("P", "J"))Pn Jython⏎
B4.30Practice2 marks

Write the output of the code.

i = 1
while i < 20:
    i *= 3
print(i)
Answer

Output:

27

Working (step by step)

LineStatementValues after this stepPrinted
1i = 1i = 1
2while i < 20:condition is True
3i *= 3i = 3
2while i < 20:condition is True
3i *= 3i = 9
2while i < 20:condition is True
3i *= 3i = 27
2while i < 20:condition is False
4print(i)27⏎
B4.31Practice2 marks

Write the output of the code.

L = [10, 20, 30]
L.insert(1, 15)
L.pop()
print(L, sum(L))
Answer

Output:

[10, 15, 20] 45

Working (step by step)

LineStatementValues after this stepPrinted
1L = [10, 20, 30]L = [10, 20, 30]
2L.insert(1, 15)L = [10, 15, 20, 30]
3L.pop()L = [10, 15, 20]
4print(L, sum(L))[10, 15, 20] 45⏎
B4.32Practice2 marks

Write the output of the code.

def f(n):
    if n % 2 == 0:
        return "Even"
    return "Odd"
print(f(7), f(10))
Answer

Output:

Odd Even

Working (step by step)

LineStatementValues after this stepPrinted
5print(f(7), f(10))n = 7
2if n % 2 == 0:condition is False
4return "Odd"n = 10
2if n % 2 == 0:condition is True
3return "Even"Odd Even⏎
B4.33Practice2 marks

Write the output of the code.

t = ()
for i in range(1, 4):
    t += (i * i,)
print(t)
Answer

Output:

(1, 4, 9)

Working (step by step)

LineStatementValues after this stepPrinted
1t = ()t = ()
2for i in range(1, 4):i = 1
3t += (i * i,)t = (1,)
2for i in range(1, 4):i = 2
3t += (i * i,)t = (1, 4)
2for i in range(1, 4):i = 3
3t += (i * i,)t = (1, 4, 9)
2for i in range(1, 4):loop ends (no more values)
4print(t)(1, 4, 9)⏎
B4.34Practice2 marks

Write the output of the code.

s = "a1b2c3"
d = 0
for ch in s:
    if ch.isdigit():
        d += int(ch)
print(d)
Answer

Output:

6

Working (step by step)

LineStatementValues after this stepPrinted
1s = "a1b2c3"s = 'a1b2c3'
2d = 0d = 0
3for ch in s:ch = 'a'
4if ch.isdigit():condition is False
3for ch in s:ch = '1'
4if ch.isdigit():condition is True
5d += int(ch)d = 1
3for ch in s:ch = 'b'
4if ch.isdigit():condition is False
3for ch in s:ch = '2'
4if ch.isdigit():condition is True
5d += int(ch)d = 3
3for ch in s:ch = 'c'
4if ch.isdigit():condition is False
3for ch in s:ch = '3'
4if ch.isdigit():condition is True

… the same steps continue for the remaining values.

B4.35Practice2 marks

Write the output of the code.

L = [4, 7, 1, 9]
m = L[0]
for x in L:
    if x > m:
        m = x
print(m, L.index(m))
Answer

Output:

9 3

Working (step by step)

LineStatementValues after this stepPrinted
1L = [4, 7, 1, 9]L = [4, 7, 1, 9]
2m = L[0]m = 4
3for x in L:x = 4
4if x > m:condition is False
3for x in L:x = 7
4if x > m:condition is True
5m = xm = 7
3for x in L:x = 1
4if x > m:condition is False
3for x in L:x = 9
4if x > m:condition is True
5m = xm = 9
3for x in L:loop ends (no more values)
6print(m, L.index(m))9 3⏎
B4.36Practice2 marks

Write the output of the code.

def add(a, b=1, c=2):
    return a + b + c
print(add(5), add(5, 5), add(1, c=10))
Answer

Output:

8 12 12

Working (step by step)

LineStatementValues after this stepPrinted
3print(add(5), add(5, 5), add(1, c=10))a = 5, b = 1, c = 2
2return a + b + cb = 5
2return a + b + ca = 1, b = 1, c = 10
2return a + b + c8 12 12⏎
B4.37Practice2 marks

Write the output of the code.

words = ["sun", "moon", "star"]
for w in words:
    print(w[0].upper() + w[1:], end=" ")
Answer

Output:

Sun Moon Star 

Working (step by step)

LineStatementValues after this stepPrinted
1words = ["sun", "moon", "star"]words = ['sun', 'moon', 'star']
2for w in words:w = 'sun'
3print(w[0].upper() + w[1:], end=" ")Sun
2for w in words:w = 'moon'
3print(w[0].upper() + w[1:], end=" ")Moon
2for w in words:w = 'star'
3print(w[0].upper() + w[1:], end=" ")Star
2for w in words:loop ends (no more values)
B4.38Practice2 marks

Write the output of the code.

x = [1, 2, 3]
y = x[:]
y.append(4)
print(len(x), len(y))
Answer

Output:

3 4

Working (step by step)

LineStatementValues after this stepPrinted
1x = [1, 2, 3]x = [1, 2, 3]
2y = x[:]y = [1, 2, 3]
3y.append(4)y = [1, 2, 3, 4]
4print(len(x), len(y))3 4⏎
B4.39Practice2 marks

Write the output of the code.

for i in range(5, 0, -2):
    print(i, end="-")
Answer

Output:

5-3-1-

Working (step by step)

LineStatementValues after this stepPrinted
1for i in range(5, 0, -2):i = 5
2print(i, end="-")5-
1for i in range(5, 0, -2):i = 3
2print(i, end="-")3-
1for i in range(5, 0, -2):i = 1
2print(i, end="-")1-
1for i in range(5, 0, -2):loop ends (no more values)
B4.40Practice2 marks

Write the output of the code.

D = {"x": 1, "y": 2}
D.update({"y": 5, "z": 9})
print(D["y"], sorted(D))
Answer

Output:

5 ['x', 'y', 'z']

Working (step by step)

LineStatementValues after this stepPrinted
1D = {"x": 1, "y": 2}D = {'x': 1, 'y': 2}
2D.update({"y": 5, "z": 9})D = {'x': 1, 'y': 5, 'z': 9}
3print(D["y"], sorted(D))5 ['x', 'y', 'z']⏎
B4.41Practice2 marks

Write the output of the code.

n = 1234
r = 0
while n > 0:
    r = r * 10 + n % 10
    n //= 10
print(r)
Answer

Output:

4321

Working (step by step)

LineStatementValues after this stepPrinted
1n = 1234n = 1234
2r = 0r = 0
3while n > 0:condition is True
4r = r * 10 + n % 10r = 4
5n //= 10n = 123
3while n > 0:condition is True
4r = r * 10 + n % 10r = 43
5n //= 10n = 12
3while n > 0:condition is True
4r = r * 10 + n % 10r = 432
5n //= 10n = 1
3while n > 0:condition is True
4r = r * 10 + n % 10r = 4321
5n //= 10n = 0
3while n > 0:condition is False
6print(r)4321⏎
B4.42Practice2 marks

Write the output of the code.

def double(L):
    for i in range(len(L)):
        L[i] = L[i] * 2
A = [1, 2, 3]
double(A)
print(A)
Answer

Output:

[2, 4, 6]

Working (step by step)

LineStatementValues after this stepPrinted
4A = [1, 2, 3]A = [1, 2, 3]
5double(A)L = [1, 2, 3]
2for i in range(len(L)):i = 0
3L[i] = L[i] * 2L = [2, 2, 3]
2for i in range(len(L)):i = 1
3L[i] = L[i] * 2L = [2, 4, 3]
2for i in range(len(L)):i = 2
3L[i] = L[i] * 2L = [2, 4, 6]
2for i in range(len(L)):A = [2, 4, 6]
6print(A)[2, 4, 6]⏎
B4.43Practice2 marks

Write the output of the code.

s = "CBSE"
for i in range(len(s) - 1, -1, -1):
    print(s[i], end="")
print()
print(len(s))
Answer

Output:

ESBC
4

Working (step by step)

LineStatementValues after this stepPrinted
1s = "CBSE"s = 'CBSE'
2for i in range(len(s) - 1, -1, -1):i = 3
3print(s[i], end="")E
2for i in range(len(s) - 1, -1, -1):i = 2
3print(s[i], end="")S
2for i in range(len(s) - 1, -1, -1):i = 1
3print(s[i], end="")B
2for i in range(len(s) - 1, -1, -1):i = 0
3print(s[i], end="")C
2for i in range(len(s) - 1, -1, -1):loop ends (no more values)
4print()⏎
5print(len(s))4⏎
B4.44Practice2 marks

Write the output of the code.

total = 0
for n in [4, 7, 10, 13]:
    if n % 2 == 0:
        continue
    total += n
print(total)
Answer

Output:

20

Working (step by step)

LineStatementValues after this stepPrinted
1total = 0total = 0
2for n in [4, 7, 10, 13]:n = 4
3if n % 2 == 0:condition is True
2for n in [4, 7, 10, 13]:n = 7
3if n % 2 == 0:condition is False
5total += ntotal = 7
2for n in [4, 7, 10, 13]:n = 10
3if n % 2 == 0:condition is True
2for n in [4, 7, 10, 13]:n = 13
3if n % 2 == 0:condition is False
5total += ntotal = 20
2for n in [4, 7, 10, 13]:loop ends (no more values)
6print(total)20⏎
B4.45Practice2 marks

Write the output of the code.

def info(name, cls="XII"):
    return name + "-" + cls
print(info("Asha"), info("Ravi", "XI"))
Answer

Output:

Asha-XII Ravi-XI

Working (step by step)

LineStatementValues after this stepPrinted
3print(info("Asha"), info("Ravi", "XI"))name = 'Asha', cls = 'XII'
2return name + "-" + clsname = 'Ravi', cls = 'XI'
2return name + "-" + clsAsha-XII Ravi-XI⏎
B5SQL commands2 marks · 61 questions
B5.1SQP 2026-272 marks

Write MySQL commands to:

  1. List all the tables of the current database
  2. Delete the database CS_SP.
Answer
SHOW TABLES;
DROP DATABASE CS_SP;
B5.2CBSE 20262 marks

Write the command to create the table W_STOCK with columns W_Code (primary key), W_Description, B_Qty and U_Price.

Answer

Use the data types and sizes given in the question paper.

CREATE TABLE W_STOCK (
  W_Code CHAR(5) PRIMARY KEY,
  W_Description VARCHAR(20),
  B_Qty INT,
  U_Price FLOAT
);

Explanation: CREATE TABLE makes the structure of a new table: each column gets a name and a data type; constraints such as PRIMARY KEY and NOT NULL set the rules.

B5.3CBSE 20262 marks

In W_STOCK, can U_Price be the primary key? Then write a command to (a) add a column E_Date of type DATE, or (b) remove the column B_Qty.

Answer

No. Two items can have the same price, so U_Price is not unique.

ALTER TABLE W_STOCK ADD E_Date DATE;
ALTER TABLE W_STOCK DROP B_Qty;
B5.4CBSE 20252 marks

In table EMPLOYEES (EMPNO, NAME, ...), (a) which column should be the primary key and why? OR (b) which constraint stops NAME from being left empty but still allows repeated names?

Answer

(a) EMPNO, because it identifies every employee uniquely while names can repeat. (b) NOT NULL.

B5.5CBSE 20252 marks

Write a command to (a) change the column BASICSAL of EMPLOYEES so that it can store values up to 99999.99, or (b) remove the table EMPLOYEES.

Answer
ALTER TABLE EMPLOYEES MODIFY BASICSAL DECIMAL(7,2);
DROP TABLE EMPLOYEES;
B5.6Practice2 marks

Write commands to:

  1. Open the database SHOP for use
  2. See the structure of the table ITEM.
Answer
USE SHOP;
DESC ITEM;
B5.7Practice2 marks

The table ITEM was created without a primary key. Write commands to:

  1. Make ICode the primary key
  2. Remove the primary key again.
Answer
ALTER TABLE ITEM ADD PRIMARY KEY (ICode);
ALTER TABLE ITEM DROP PRIMARY KEY;
B5.8Practice2 marks

Write commands to:

  1. Insert the row (105, 'Pen', 12.5) into ITEM
  2. Delete all the items whose price is more than 500.
Answer
INSERT INTO ITEM VALUES (105, 'Pen', 12.5);
DELETE FROM ITEM WHERE Price > 500;
B5.9Practice2 marks

Write commands to:

  1. Add a column Phone of type CHAR(10) to the table MEMBER
  2. Change the data type of MName to VARCHAR(40).
Answer
ALTER TABLE MEMBER ADD Phone CHAR(10);
ALTER TABLE MEMBER MODIFY MName VARCHAR(40);
B5.10Practice2 marks

Write commands to:

  1. Create a database LIBRARY
  2. List all the databases on the server.
Answer
CREATE DATABASE LIBRARY;
SHOW DATABASES;
B5.11Practice2 marks

Write the command to create the table MEMBER: MNo integer primary key, MName up to 25 characters and compulsory, Phone 10 characters with no repeats, DOJ date.

Answer
CREATE TABLE MEMBER (
  MNo INT PRIMARY KEY,
  MName VARCHAR(25) NOT NULL,
  Phone CHAR(10) UNIQUE,
  DOJ DATE
);

Explanation: CREATE TABLE makes the structure of a new table: each column gets a name and a data type; constraints such as PRIMARY KEY and NOT NULL set the rules.

B5.12Practice2 marks

For the table TEACHER (TNo, TName, Subject, Salary, City), write commands to:

  1. Add a column Email of type VARCHAR(30)
  2. Remove the column City.
Answer
ALTER TABLE TEACHER ADD Email VARCHAR(30);
ALTER TABLE TEACHER DROP COLUMN City;
B5.13Practice2 marks

For the table TEACHER (TNo, TName, Subject, Salary, City), write commands to:

  1. Change the column TName so that it can hold 40 characters
  2. Display the structure of the table.
Answer
ALTER TABLE TEACHER MODIFY TName VARCHAR(40);
DESC TEACHER;
B5.14Practice2 marks

The table TEACHER (TNo, TName, Subject, Salary, City) was created without a primary key. Write commands to:

  1. Make TNo the primary key
  2. Insert the row 1, 'Sunita', 'Maths', 52000, 'Delhi'.
Answer
ALTER TABLE TEACHER ADD PRIMARY KEY (TNo);
INSERT INTO TEACHER VALUES (1, 'Sunita', 'Maths', 52000, 'Delhi');
B5.15Practice2 marks

For the table MOVIE (MNo, Title, Language, Rating, Tickets), write commands to:

  1. Add a column Director of type VARCHAR(25)
  2. Remove the column Tickets.
Answer
ALTER TABLE MOVIE ADD Director VARCHAR(25);
ALTER TABLE MOVIE DROP COLUMN Tickets;
B5.16Practice2 marks

For the table MOVIE (MNo, Title, Language, Rating, Tickets), write commands to:

  1. Change the column Title so that it can hold 40 characters
  2. Display the structure of the table.
Answer
ALTER TABLE MOVIE MODIFY Title VARCHAR(40);
DESC MOVIE;
B5.17Practice2 marks

The table MOVIE (MNo, Title, Language, Rating, Tickets) was created without a primary key. Write commands to:

  1. Make MNo the primary key
  2. Insert the row 1, 'Udaan', 'Hindi', 8, 450.
Answer
ALTER TABLE MOVIE ADD PRIMARY KEY (MNo);
INSERT INTO MOVIE VALUES (1, 'Udaan', 'Hindi', 8, 450);
B5.18Practice2 marks

For the table FLIGHT (FNo, Airline, Source, Seats, Fare), write commands to:

  1. Add a column Dest of type VARCHAR(20)
  2. Remove the column Fare.
Answer
ALTER TABLE FLIGHT ADD Dest VARCHAR(20);
ALTER TABLE FLIGHT DROP COLUMN Fare;
B5.19Practice2 marks

For the table FLIGHT (FNo, Airline, Source, Seats, Fare), write commands to:

  1. Change the column FNo so that it can hold 40 characters
  2. Display the structure of the table.
Answer
ALTER TABLE FLIGHT MODIFY FNo VARCHAR(40);
DESC FLIGHT;
B5.20Practice2 marks

The table FLIGHT (FNo, Airline, Source, Seats, Fare) was created without a primary key. Write commands to:

  1. Make FNo the primary key
  2. Insert the row 'F101', 'SkyJet', 'Delhi', 180, 5200.
Answer
ALTER TABLE FLIGHT ADD PRIMARY KEY (FNo);
INSERT INTO FLIGHT VALUES ('F101', 'SkyJet', 'Delhi', 180, 5200);
B5.21Practice2 marks

For the table MOBILE (MID, Model, Brand, Price, Stock), write commands to:

  1. Add a column Colour of type VARCHAR(15)
  2. Remove the column Stock.
Answer
ALTER TABLE MOBILE ADD Colour VARCHAR(15);
ALTER TABLE MOBILE DROP COLUMN Stock;
B5.22Practice2 marks

For the table MOBILE (MID, Model, Brand, Price, Stock), write commands to:

  1. Change the column Model so that it can hold 40 characters
  2. Display the structure of the table.
Answer
ALTER TABLE MOBILE MODIFY Model VARCHAR(40);
DESC MOBILE;
B5.23Practice2 marks

The table MOBILE (MID, Model, Brand, Price, Stock) was created without a primary key. Write commands to:

  1. Make MID the primary key
  2. Insert the row 1, 'Nova 5', 'Zen', 12000, 30.
Answer
ALTER TABLE MOBILE ADD PRIMARY KEY (MID);
INSERT INTO MOBILE VALUES (1, 'Nova 5', 'Zen', 12000, 30);
B5.24Practice2 marks

For the table PATIENT (PID, PName, Ward, Days, Bill), write commands to:

  1. Add a column Doctor of type VARCHAR(25)
  2. Remove the column Bill.
Answer
ALTER TABLE PATIENT ADD Doctor VARCHAR(25);
ALTER TABLE PATIENT DROP COLUMN Bill;
B5.25Practice2 marks

For the table PATIENT (PID, PName, Ward, Days, Bill), write commands to:

  1. Change the column PName so that it can hold 40 characters
  2. Display the structure of the table.
Answer
ALTER TABLE PATIENT MODIFY PName VARCHAR(40);
DESC PATIENT;
B5.26Practice2 marks

The table PATIENT (PID, PName, Ward, Days, Bill) was created without a primary key. Write commands to:

  1. Make PID the primary key
  2. Insert the row 1, 'Mohan', 'General', 3, 4500.
Answer
ALTER TABLE PATIENT ADD PRIMARY KEY (PID);
INSERT INTO PATIENT VALUES (1, 'Mohan', 'General', 3, 4500);
B5.27Practice2 marks

For the table CLUB (MemNo, MName, Sport, Fee, Age), write commands to:

  1. Add a column Phone of type CHAR(10)
  2. Remove the column Age.
Answer
ALTER TABLE CLUB ADD Phone CHAR(10);
ALTER TABLE CLUB DROP COLUMN Age;
B5.28Practice2 marks

For the table CLUB (MemNo, MName, Sport, Fee, Age), write commands to:

  1. Change the column MName so that it can hold 40 characters
  2. Display the structure of the table.
Answer
ALTER TABLE CLUB MODIFY MName VARCHAR(40);
DESC CLUB;
B5.29Practice2 marks

The table CLUB (MemNo, MName, Sport, Fee, Age) was created without a primary key. Write commands to:

  1. Make MemNo the primary key
  2. Insert the row 1, 'Arjun', 'Cricket', 1500, 16.
Answer
ALTER TABLE CLUB ADD PRIMARY KEY (MemNo);
INSERT INTO CLUB VALUES (1, 'Arjun', 'Cricket', 1500, 16);
B5.30Practice2 marks

For the table GARMENT (GCode, GName, Size, Price, Qty), write commands to:

  1. Add a column Fabric of type VARCHAR(15)
  2. Remove the column Qty.
Answer
ALTER TABLE GARMENT ADD Fabric VARCHAR(15);
ALTER TABLE GARMENT DROP COLUMN Qty;
B5.31Practice2 marks

For the table GARMENT (GCode, GName, Size, Price, Qty), write commands to:

  1. Change the column GName so that it can hold 40 characters
  2. Display the structure of the table.
Answer
ALTER TABLE GARMENT MODIFY GName VARCHAR(40);
DESC GARMENT;
B5.32Practice2 marks

The table GARMENT (GCode, GName, Size, Price, Qty) was created without a primary key. Write commands to:

  1. Make GCode the primary key
  2. Insert the row 'G1', 'Kurta', 'M', 650, 20.
Answer
ALTER TABLE GARMENT ADD PRIMARY KEY (GCode);
INSERT INTO GARMENT VALUES ('G1', 'Kurta', 'M', 650, 20);
B5.33Practice2 marks

For the table COURSE (CID, CName, Mode, Fees, Seats), write commands to:

  1. Add a column Duration of type INT
  2. Remove the column Seats.
Answer
ALTER TABLE COURSE ADD Duration INT;
ALTER TABLE COURSE DROP COLUMN Seats;
B5.34Practice2 marks

For the table COURSE (CID, CName, Mode, Fees, Seats), write commands to:

  1. Change the column CName so that it can hold 40 characters
  2. Display the structure of the table.
Answer
ALTER TABLE COURSE MODIFY CName VARCHAR(40);
DESC COURSE;
B5.35Practice2 marks

The table COURSE (CID, CName, Mode, Fees, Seats) was created without a primary key. Write commands to:

  1. Make CID the primary key
  2. Insert the row 'C1', 'Python Basics', 'Online', 3000, 60.
Answer
ALTER TABLE COURSE ADD PRIMARY KEY (CID);
INSERT INTO COURSE VALUES ('C1', 'Python Basics', 'Online', 3000, 60);
B5.36Practice2 marks

For the table HOSTEL (RoomNo, SName, Block, Rent, Sem), write commands to:

  1. Add a column Mess of type CHAR(3)
  2. Remove the column Sem.
Answer
ALTER TABLE HOSTEL ADD Mess CHAR(3);
ALTER TABLE HOSTEL DROP COLUMN Sem;
B5.37Practice2 marks

For the table HOSTEL (RoomNo, SName, Block, Rent, Sem), write commands to:

  1. Change the column SName so that it can hold 40 characters
  2. Display the structure of the table.
Answer
ALTER TABLE HOSTEL MODIFY SName VARCHAR(40);
DESC HOSTEL;
B5.38Practice2 marks

The table HOSTEL (RoomNo, SName, Block, Rent, Sem) was created without a primary key. Write commands to:

  1. Make RoomNo the primary key
  2. Insert the row 101, 'Kiran', 'A', 4000, 1.
Answer
ALTER TABLE HOSTEL ADD PRIMARY KEY (RoomNo);
INSERT INTO HOSTEL VALUES (101, 'Kiran', 'A', 4000, 1);
B5.39Practice2 marks

For the table BUS (BusNo, Route, Depot, Seats, Fare), write commands to:

  1. Add a column Driver of type VARCHAR(25)
  2. Remove the column Fare.
Answer
ALTER TABLE BUS ADD Driver VARCHAR(25);
ALTER TABLE BUS DROP COLUMN Fare;
B5.40Practice2 marks

For the table BUS (BusNo, Route, Depot, Seats, Fare), write commands to:

  1. Change the column Route so that it can hold 40 characters
  2. Display the structure of the table.
Answer
ALTER TABLE BUS MODIFY Route VARCHAR(40);
DESC BUS;
B5.41Practice2 marks

The table BUS (BusNo, Route, Depot, Seats, Fare) was created without a primary key. Write commands to:

  1. Make BusNo the primary key
  2. Insert the row 'B1', 'Airport Link', 'North', 40, 60.
Answer
ALTER TABLE BUS ADD PRIMARY KEY (BusNo);
INSERT INTO BUS VALUES ('B1', 'Airport Link', 'North', 40, 60);
B5.42Practice2 marks

For the table TEACHER (TNo, TName, Subject, Salary, City), write commands to:

  1. Delete the teachers whose Salary is less than 45000
  2. Remove the table completely.
Answer
DELETE FROM TEACHER WHERE Salary < 45000;
DROP TABLE TEACHER;
B5.43Practice2 marks

Write the command to create the table TEACHER with the columns TNo, TName, Subject, Salary, City. TNo is the primary key and TName cannot be left empty. Then write the command to insert the row 2, 'Rakesh', 'Physics', 61000, 'Agra'.

Answer
CREATE TABLE TEACHER (
  TNo INT PRIMARY KEY,
  TName VARCHAR(20) NOT NULL,
  Subject VARCHAR(20),
  Salary INT,
  City VARCHAR(20)
);
INSERT INTO TEACHER VALUES (2, 'Rakesh', 'Physics', 61000, 'Agra');
B5.44Practice2 marks

For the table MOVIE (MNo, Title, Language, Rating, Tickets), write commands to:

  1. Delete the movies whose Tickets is less than 250
  2. Remove the table completely.
Answer
DELETE FROM MOVIE WHERE Tickets < 250;
DROP TABLE MOVIE;
B5.45Practice2 marks

Write the command to create the table MOVIE with the columns MNo, Title, Language, Rating, Tickets. MNo is the primary key and Title cannot be left empty. Then write the command to insert the row 2, 'Sagar', 'Tamil', 7, 300.

Answer
CREATE TABLE MOVIE (
  MNo INT PRIMARY KEY,
  Title VARCHAR(20) NOT NULL,
  Language VARCHAR(20),
  Rating INT,
  Tickets INT
);
INSERT INTO MOVIE VALUES (2, 'Sagar', 'Tamil', 7, 300);
B5.46Practice2 marks

For the table FLIGHT (FNo, Airline, Source, Seats, Fare), write commands to:

  1. Delete the flights whose Fare is less than 4500
  2. Remove the table completely.
Answer
DELETE FROM FLIGHT WHERE Fare < 4500;
DROP TABLE FLIGHT;
B5.47Practice2 marks

Write the command to create the table FLIGHT with the columns FNo, Airline, Source, Seats, Fare. FNo is the primary key and FNo cannot be left empty. Then write the command to insert the row 'F102', 'AirWing', 'Mumbai', 150, 4800.

Answer
CREATE TABLE FLIGHT (
  FNo VARCHAR(20) PRIMARY KEY,
  Airline VARCHAR(20),
  Source VARCHAR(20),
  Seats INT,
  Fare INT
);
INSERT INTO FLIGHT VALUES ('F102', 'AirWing', 'Mumbai', 150, 4800);
B5.48Practice2 marks

For the table MOBILE (MID, Model, Brand, Price, Stock), write commands to:

  1. Delete the mobiles whose Price is less than 10000
  2. Remove the table completely.
Answer
DELETE FROM MOBILE WHERE Price < 10000;
DROP TABLE MOBILE;
B5.49Practice2 marks

Write the command to create the table MOBILE with the columns MID, Model, Brand, Price, Stock. MID is the primary key and Model cannot be left empty. Then write the command to insert the row 2, 'Alpha X', 'Orbit', 18500, 12.

Answer
CREATE TABLE MOBILE (
  MID INT PRIMARY KEY,
  Model VARCHAR(20) NOT NULL,
  Brand VARCHAR(20),
  Price INT,
  Stock INT
);
INSERT INTO MOBILE VALUES (2, 'Alpha X', 'Orbit', 18500, 12);
B5.50Practice2 marks

For the table PATIENT (PID, PName, Ward, Days, Bill), write commands to:

  1. Delete the patients whose Bill is less than 5000
  2. Remove the table completely.
Answer
DELETE FROM PATIENT WHERE Bill < 5000;
DROP TABLE PATIENT;
B5.51Practice2 marks

Write the command to create the table PATIENT with the columns PID, PName, Ward, Days, Bill. PID is the primary key and PName cannot be left empty. Then write the command to insert the row 2, 'Rekha', 'ICU', 5, 32000.

Answer
CREATE TABLE PATIENT (
  PID INT PRIMARY KEY,
  PName VARCHAR(20) NOT NULL,
  Ward VARCHAR(20),
  Days INT,
  Bill INT
);
INSERT INTO PATIENT VALUES (2, 'Rekha', 'ICU', 5, 32000);
B5.52Practice2 marks

For the table CLUB (MemNo, MName, Sport, Fee, Age), write commands to:

  1. Delete the members whose Fee is less than 1000
  2. Remove the table completely.
Answer
DELETE FROM CLUB WHERE Fee < 1000;
DROP TABLE CLUB;
B5.53Practice2 marks

Write the command to create the table CLUB with the columns MemNo, MName, Sport, Fee, Age. MemNo is the primary key and MName cannot be left empty. Then write the command to insert the row 2, 'Nisha', 'Tennis', 2200, 15.

Answer
CREATE TABLE CLUB (
  MemNo INT PRIMARY KEY,
  MName VARCHAR(20) NOT NULL,
  Sport VARCHAR(20),
  Fee INT,
  Age INT
);
INSERT INTO CLUB VALUES (2, 'Nisha', 'Tennis', 2200, 15);
B5.54Practice2 marks

For the table GARMENT (GCode, GName, Size, Price, Qty), write commands to:

  1. Delete the garments whose Price is less than 750
  2. Remove the table completely.
Answer
DELETE FROM GARMENT WHERE Price < 750;
DROP TABLE GARMENT;
B5.55Practice2 marks

Write the command to create the table GARMENT with the columns GCode, GName, Size, Price, Qty. GCode is the primary key and GName cannot be left empty. Then write the command to insert the row 'G2', 'Jeans', 'L', 1200, 15.

Answer
CREATE TABLE GARMENT (
  GCode VARCHAR(20) PRIMARY KEY,
  GName VARCHAR(20) NOT NULL,
  Size VARCHAR(20),
  Price INT,
  Qty INT
);
INSERT INTO GARMENT VALUES ('G2', 'Jeans', 'L', 1200, 15);
B5.56Practice2 marks

For the table COURSE (CID, CName, Mode, Fees, Seats), write commands to:

  1. Delete the courses whose Fees is less than 4000
  2. Remove the table completely.
Answer
DELETE FROM COURSE WHERE Fees < 4000;
DROP TABLE COURSE;
B5.57Practice2 marks

Write the command to create the table COURSE with the columns CID, CName, Mode, Fees, Seats. CID is the primary key and CName cannot be left empty. Then write the command to insert the row 'C2', 'Data Science', 'Offline', 12000, 30.

Answer
CREATE TABLE COURSE (
  CID VARCHAR(20) PRIMARY KEY,
  CName VARCHAR(20) NOT NULL,
  Mode VARCHAR(20),
  Fees INT,
  Seats INT
);
INSERT INTO COURSE VALUES ('C2', 'Data Science', 'Offline', 12000, 30);
B5.58Practice2 marks

For the table HOSTEL (RoomNo, SName, Block, Rent, Sem), write commands to:

  1. Delete the students whose Rent is less than 4400
  2. Remove the table completely.
Answer
DELETE FROM HOSTEL WHERE Rent < 4400;
DROP TABLE HOSTEL;
B5.59Practice2 marks

Write the command to create the table HOSTEL with the columns RoomNo, SName, Block, Rent, Sem. RoomNo is the primary key and SName cannot be left empty. Then write the command to insert the row 102, 'Deepa', 'B', 4500, 2.

Answer
CREATE TABLE HOSTEL (
  RoomNo INT PRIMARY KEY,
  SName VARCHAR(20) NOT NULL,
  Block VARCHAR(20),
  Rent INT,
  Sem INT
);
INSERT INTO HOSTEL VALUES (102, 'Deepa', 'B', 4500, 2);
B5.60Practice2 marks

For the table BUS (BusNo, Route, Depot, Seats, Fare), write commands to:

  1. Delete the buses whose Fare is less than 30
  2. Remove the table completely.
Answer
DELETE FROM BUS WHERE Fare < 30;
DROP TABLE BUS;
B5.61Practice2 marks

Write the command to create the table BUS with the columns BusNo, Route, Depot, Seats, Fare. BusNo is the primary key and Route cannot be left empty. Then write the command to insert the row 'B2', 'City Circle', 'South', 52, 25.

Answer
CREATE TABLE BUS (
  BusNo VARCHAR(20) PRIMARY KEY,
  Route VARCHAR(20) NOT NULL,
  Depot VARCHAR(20),
  Seats INT,
  Fare INT
);
INSERT INTO BUS VALUES ('B2', 'City Circle', 'South', 52, 25);
B6Network short answers2 marks · 43 questions
B6.1SQP 2026-272 marks

Name the protocol used to browse web pages. Also name any one web browser.

Answer

HTTP (HyperText Transfer Protocol); its secure form is HTTPS. Browsers: Google Chrome, Mozilla Firefox, Microsoft Edge.

B6.2SQP 2026-272 marks

Define tree topology. Write one limitation of it.

Answer

In tree topology, groups of star-connected computers are joined to a main backbone cable in a hierarchy. Limitation: if the backbone fails, all the branches connected to it stop working.

B6.3CBSE 20262 marks

Write one advantage and one disadvantage of bus topology.

Answer

Advantage: simple and cheap, because it needs the least cable. Disadvantage: if the backbone cable fails, the whole network stops, and faults are hard to locate.

B6.4CBSE 20262 marks

What is a protocol in computer networks? Name the protocol used to transfer hypertext on the web.

Answer

A protocol is a set of rules that devices follow to communicate over a network. Hypertext is transferred with HTTP (or HTTPS).

B6.5CBSE 20252 marks

Expand URL and explain it.

Answer

Uniform Resource Locator. It is the unique address of a resource (web page, image, file) on the Internet, for example https://www.cbse.gov.in/index.html.

B6.6CBSE 20252 marks

Expand PPP and explain it.

Answer

Point-to-Point Protocol. It sets up a direct connection between two devices, for example between a computer and an Internet service provider.

B6.7Practice2 marks

Differentiate between a hub and a switch.

Answer

A hub sends the data it receives to all the connected devices, so traffic is high. A switch reads the destination address and sends the data only to that device, so it is faster and more secure.

B6.8Practice2 marks

Differentiate between LAN and WAN.

Answer

LAN covers a small area such as a room, building or campus; it is fast and privately owned. WAN covers cities and countries; it uses public links such as telephone lines and satellites and is slower. The Internet is the largest WAN.

B6.9Practice2 marks

Differentiate between circuit switching and packet switching.

Answer

In circuit switching a dedicated path is set up first and stays reserved for the whole communication. In packet switching the message is broken into packets; each packet may travel by a different route and they are put together at the destination.

B6.10Practice2 marks

Expand SMTP and POP3. Write the use of each.

Answer

SMTP: Simple Mail Transfer Protocol, used for sending e-mail. POP3: Post Office Protocol version 3, used for receiving (downloading) e-mail from the mail server.

B6.11Practice2 marks

Differentiate between a web browser and a web server.

Answer

A web browser is client software that requests and displays web pages (Chrome, Firefox). A web server is a computer or program that stores websites and sends the pages to browsers on request (Apache, IIS).

B6.12Practice2 marks

Differentiate between HTML and XML.

Answer

HTML displays data; its tags are fixed (predefined). XML stores and carries data; the user makes his or her own tags, and the tags are case-sensitive.

B6.13Practice2 marks

What is web hosting? What is a domain name? Give one example.

Answer

Web hosting is the service of storing a website on a web server so that it can be opened on the Internet. A domain name is the easy-to-remember name of a website that stands for its IP address, for example cbse.gov.in.

B6.14Practice2 marks

What is a computer network? Write two advantages.

Answer

A computer network is a group of computers and devices connected to share data and resources. Advantages: sharing of files and printers; fast communication through e-mail and chat.

B6.15Practice2 marks

Expand LAN and MAN. Give one example of each.

Answer

LAN: Local Area Network, e.g. the computers of a school lab. MAN: Metropolitan Area Network, e.g. a cable TV network of a city.

B6.16Practice2 marks

What is a modem? Why is it needed?

Answer

A modem (MOdulator-DEModulator) changes digital signals of a computer into analog signals for the telephone line and back. It is needed to connect a computer or network to the Internet.

B6.17Practice2 marks

Differentiate between a router and a switch.

Answer

A switch connects the computers inside one network. A router connects different networks (for example a LAN to the Internet) and chooses the best path for the data.

B6.18Practice2 marks

What is a gateway?

Answer

A gateway is a device that connects two networks that use different protocols. It is the entry and exit point of a network.

B6.19Practice2 marks

What is the role of a repeater? When is it needed?

Answer

A repeater regenerates a weak signal and sends it ahead. It is needed when the cable between two points is long (more than about 100 m), because signals become weak with distance.

B6.20Practice2 marks

Write one advantage and one disadvantage of star topology.

Answer

Advantage: a fault in one cable affects only that computer, and faults are easy to find. Disadvantage: if the central hub or switch fails, the whole network stops; it also needs more cable.

B6.21Practice2 marks

Differentiate between bus topology and star topology.

Answer

In bus topology all computers share one backbone cable; it is cheap but one cable fault stops everything. In star topology every computer has its own cable to a central device; it costs more but is more reliable.

B6.22Practice2 marks

Differentiate between twisted pair cable and optical fibre.

Answer

Twisted pair is cheap, carries electrical signals, and suits short distances. Optical fibre is costly, carries light signals, is very fast, and suits long distances.

B6.23Practice2 marks

Write two advantages of optical fibre cable.

Answer

It has very high speed and bandwidth. It is not affected by electrical or magnetic interference and is secure.

B6.24Practice2 marks

Differentiate between radio waves and infrared waves.

Answer

Radio waves travel long distances in all directions and pass through walls. Infrared waves work over a very short distance and cannot pass through walls, e.g. a TV remote.

B6.25Practice2 marks

Write one feature and one limitation of microwave communication.

Answer

Feature: it carries data over long distances without cables, using towers. Limitation: the towers must be in line of sight, and bad weather affects the signal.

B6.26Practice2 marks

What is bandwidth? In which unit is it measured?

Answer

Bandwidth is the range of frequencies that a channel can carry. It is measured in Hertz (Hz, kHz, MHz). More bandwidth means more data can be sent.

B6.27Practice2 marks

What is data transfer rate? Name two units.

Answer

It is the amount of data transferred in one second. Units: bps (bits per second), Kbps, Mbps, Gbps.

B6.28Practice2 marks

Differentiate between an IP address and a MAC address.

Answer

An IP address is the logical address of a device on a network; it can change. A MAC address is the 48-bit physical address fixed on the network card by its maker; it does not change.

B6.29Practice2 marks

Expand TCP/IP. What is its role?

Answer

Transmission Control Protocol / Internet Protocol. TCP breaks the data into packets and puts them together again; IP gives the addresses and routes the packets. It is the basic protocol of the Internet.

B6.30Practice2 marks

Expand FTP. Write its use.

Answer

File Transfer Protocol. It is used to upload and download files between a computer and a server.

B6.31Practice2 marks

Differentiate between HTTP and HTTPS.

Answer

HTTP transfers web pages as plain data. HTTPS is the secure form; it encrypts the data, so it is used for banking and payments.

B6.32Practice2 marks

What is TELNET?

Answer

TELNET is a protocol for remote login. A user can connect to a distant computer and work on it as if sitting in front of it.

B6.33Practice2 marks

Expand VoIP. Write one use.

Answer

Voice over Internet Protocol. It carries voice and video calls over the Internet, e.g. video conferencing and Internet calling.

B6.34Practice2 marks

Differentiate between a web page and a website.

Answer

A web page is a single document written in HTML. A website is a collection of related web pages under one domain name.

B6.35Practice2 marks

Differentiate between the Internet and the WWW.

Answer

The Internet is the worldwide network of connected computers. The WWW is one service that runs on the Internet: the collection of linked web pages.

B6.36Practice2 marks

What is a URL? Name its parts with an example.

Answer

A URL (Uniform Resource Locator) is the address of a resource on the web. In https://www.cbse.gov.in/index.html: https is the protocol, www.cbse.gov.in is the domain name, index.html is the file name.

B6.37Practice2 marks

What is a domain name? Give an example.

Answer

A domain name is the easy-to-remember name of a website that stands for the IP address of its server, e.g. kvsangathan.nic.in.

B6.38Practice2 marks

What is a web server?

Answer

A web server is a computer (or the program on it) that stores websites and sends the requested web pages to the browsers of users.

B6.39Practice2 marks

What is a web browser? Give two examples.

Answer

A web browser is software used to open and view web pages. Examples: Google Chrome, Mozilla Firefox.

B6.40Practice2 marks

Write short notes on ARPANET and NSFNET.

Answer

ARPANET (1969) was the first network, started by the US Department of Defense. NSFNET was a faster network started by the National Science Foundation for research and education. Together they grew into the Internet.

B6.41Practice2 marks

What is packet switching? Write one advantage.

Answer

In packet switching the message is divided into small packets; each packet may travel by a different route and they are joined at the destination. Advantage: the line is shared, so it is used efficiently.

B6.42Practice2 marks

What is a PAN? Give an example.

Answer

A PAN (Personal Area Network) connects the devices of one person within a few metres, e.g. a phone connected to a Bluetooth speaker.

B6.43Practice2 marks

What is the function of an Ethernet card? What is RJ45?

Answer

An Ethernet card (NIC) connects a computer to a wired network and has a unique MAC address. RJ45 (Registered Jack 45) is the eight-pin connector at the end of an Ethernet cable.

Section C · 3 marks each

C1Text file functions3 marks · 42 questions
C1.1SQP 2026-273 marks

Write a function DisplayYearLines() that displays the lines of History.txt which contain a four-digit year such as 1999 or 2024. Also call the function.

Answer
def DisplayYearLines():
    f = open("History.txt", "r")
    for line in f:
        for w in line.split():
            w = w.strip(".,;:()")
            if w.isdigit() and len(w) == 4:
                print(line, end="")
                break
    f.close()

DisplayYearLines()
C1.2SQP 2026-273 marks

Write a function that counts how many times the word "Python" occurs in Prog.txt.

Answer
def count_python():
    f = open("Prog.txt", "r")
    c = 0
    for w in f.read().split():
        if w == "Python":
            c += 1
    print(c)
    f.close()
C1.3CBSE 20263 marks

Write a function that counts the digits present in the text file Space.txt.

Answer
def count_digits():
    f = open("Space.txt", "r")
    c = 0
    for ch in f.read():
        if ch.isdigit():
            c += 1
    print(c)
    f.close()
C1.4CBSE 20263 marks

Write a function that displays the words of Space.txt in which the small letter 'e' occurs at least twice.

Answer
def show_e_words():
    f = open("Space.txt", "r")
    for w in f.read().split():
        if w.count("e") >= 2:
            print(w, end=" ")
    f.close()
C1.5CBSE 20253 marks

Write a function that displays the lines of Elections.txt which contain the word "vote".

Answer
def show_vote():
    f = open("Elections.txt", "r")
    for line in f:
        if "vote" in line.lower().split():
            print(line, end="")
    f.close()
C1.6CBSE 20253 marks

Write a function that displays the words of Report.txt which start and end with a vowel.

Answer
def vowel_words():
    f = open("Report.txt", "r")
    v = "aeiouAEIOU"
    for w in f.read().split():
        if w[0] in v and w[-1] in v:
            print(w, end=" ")
    f.close()
C1.7Practice3 marks

Write a function that counts the lines of Story.txt which start with the letter 'T'.

Answer
def count_T():
    f = open("Story.txt", "r")
    c = 0
    for line in f:
        if line[0] == "T":
            c += 1
    print("Lines starting with T:", c)
    f.close()
C1.8Practice3 marks

Write a function that counts the vowels and the consonants in Poem.txt.

Answer
def count_vc():
    f = open("Poem.txt", "r")
    v = c = 0
    for ch in f.read():
        if ch.isalpha():
            if ch in "aeiouAEIOU":
                v += 1
            else:
                c += 1
    print("Vowels:", v, "Consonants:", c)
    f.close()
C1.9Practice3 marks

Write a function that displays the words of Notes.txt which have more than 5 characters.

Answer
def long_words():
    f = open("Notes.txt", "r")
    for w in f.read().split():
        if len(w) > 5:
            print(w)
    f.close()
C1.10Practice3 marks

Write a function that counts the word "the" in Para.txt. Count "The" and "THE" also.

Answer
def count_the():
    f = open("Para.txt", "r")
    c = 0
    for w in f.read().split():
        if w.lower() == "the":
            c += 1
    print(c)
    f.close()
C1.11Practice3 marks

Write a function that copies those lines of Old.txt which do not contain the letter 'a' into New.txt.

Answer
def copy_lines():
    f1 = open("Old.txt", "r")
    f2 = open("New.txt", "w")
    for line in f1:
        if "a" not in line:
            f2.write(line)
    f1.close()
    f2.close()
C1.12Practice3 marks

Write a function that displays the number of lines, words and characters in Data.txt.

Answer
def file_stats():
    f = open("Data.txt", "r")
    data = f.read()
    f.close()
    print("Lines:", len(data.splitlines()))
    print("Words:", len(data.split()))
    print("Characters:", len(data))
C1.13Practice3 marks

Write a function count_chars() that counts the capital letters in the text file Diary.txt and displays the count.

Answer
def count_chars():
    f = open("Diary.txt", "r")
    c = 0
    for ch in f.read():
        if ch.isupper():
            c += 1
    print(c)
    f.close()
C1.14Practice3 marks

Write a function count_chars() that counts the small letters in the text file Memo.txt and displays the count.

Answer
def count_chars():
    f = open("Memo.txt", "r")
    c = 0
    for ch in f.read():
        if ch.islower():
            c += 1
    print(c)
    f.close()
C1.15Practice3 marks

Write a function count_chars() that counts the spaces in the text file Essay.txt and displays the count.

Answer
def count_chars():
    f = open("Essay.txt", "r")
    c = 0
    for ch in f.read():
        if ch == " ":
            c += 1
    print(c)
    f.close()
C1.16Practice3 marks

Write a function count_chars() that counts the vowels in the text file Speech.txt and displays the count.

Answer
def count_chars():
    f = open("Speech.txt", "r")
    c = 0
    for ch in f.read():
        if ch in "aeiouAEIOU":
            c += 1
    print(c)
    f.close()
C1.17Practice3 marks

Write a function count_chars() that counts the letters "a" and "A" in the text file Letter.txt and displays the count.

Answer
def count_chars():
    f = open("Letter.txt", "r")
    c = 0
    for ch in f.read():
        if ch in "aA":
            c += 1
    print(c)
    f.close()
C1.18Practice3 marks

Write a function count_chars() that counts the consonants in the text file Rules.txt and displays the count.

Answer
def count_chars():
    f = open("Rules.txt", "r")
    c = 0
    for ch in f.read():
        if ch.isalpha() and ch not in "aeiouAEIOU":
            c += 1
    print(c)
    f.close()
C1.19Practice3 marks

Write a function count_words() that counts the words that start with a capital letter in the text file News.txt and displays the count.

Answer
def count_words():
    f = open("News.txt", "r")
    c = 0
    for w in f.read().split():
        if w[0].isupper():
            c += 1
    print(c)
    f.close()
C1.20Practice3 marks

Write a function count_words() that counts the words that have exactly 4 characters in the text file Blog.txt and displays the count.

Answer
def count_words():
    f = open("Blog.txt", "r")
    c = 0
    for w in f.read().split():
        if len(w) == 4:
            c += 1
    print(c)
    f.close()
C1.21Practice3 marks

Write a function count_words() that counts the words that end with "s" in the text file Quote.txt and displays the count.

Answer
def count_words():
    f = open("Quote.txt", "r")
    c = 0
    for w in f.read().split():
        if w.endswith("s"):
            c += 1
    print(c)
    f.close()
C1.22Practice3 marks

Write a function count_words() that counts the words that begin with "t" or "T" in the text file Fable.txt and displays the count.

Answer
def count_words():
    f = open("Fable.txt", "r")
    c = 0
    for w in f.read().split():
        if w[0] in "tT":
            c += 1
    print(c)
    f.close()
C1.23Practice3 marks

Write a function count_words() that counts the word "is" (in capital or small letters) in the text file Lesson.txt and displays the count.

Answer
def count_words():
    f = open("Lesson.txt", "r")
    c = 0
    for w in f.read().split():
        if w.lower() == "is":
            c += 1
    print(c)
    f.close()
C1.24Practice3 marks

Write a function count_words() that counts the words that are numbers (made only of digits) in the text file Notice.txt and displays the count.

Answer
def count_words():
    f = open("Notice.txt", "r")
    c = 0
    for w in f.read().split():
        if w.isdigit():
            c += 1
    print(c)
    f.close()
C1.25Practice3 marks

Write a function show_words() that displays the words that have more than 6 characters from the text file Song.txt.

Answer
def show_words():
    f = open("Song.txt", "r")
    for w in f.read().split():
        if len(w) > 6:
            print(w, end=" ")
    f.close()
C1.26Practice3 marks

Write a function show_words() that displays the words that start with a vowel from the text file Tale.txt.

Answer
def show_words():
    f = open("Tale.txt", "r")
    for w in f.read().split():
        if w[0] in "aeiouAEIOU":
            print(w, end=" ")
    f.close()
C1.27Practice3 marks

Write a function show_words() that displays the words written fully in capital letters from the text file Riddle.txt.

Answer
def show_words():
    f = open("Riddle.txt", "r")
    for w in f.read().split():
        if w.isupper():
            print(w, end=" ")
    f.close()
C1.28Practice3 marks

Write a function show_words() that displays the words that start and end with the same letter from the text file Chapter.txt.

Answer
def show_words():
    f = open("Chapter.txt", "r")
    for w in f.read().split():
        if w[0].lower() == w[-1].lower():
            print(w, end=" ")
    f.close()
C1.29Practice3 marks

Write a function show_words() that displays the words that contain the letter "e" exactly once from the text file Recipe.txt.

Answer
def show_words():
    f = open("Recipe.txt", "r")
    for w in f.read().split():
        if w.count("e") == 1:
            print(w, end=" ")
    f.close()
C1.30Practice3 marks

Write a function show_words() that displays the words that have fewer than 3 characters from the text file Motto.txt.

Answer
def show_words():
    f = open("Motto.txt", "r")
    for w in f.read().split():
        if len(w) < 3:
            print(w, end=" ")
    f.close()
C1.31Practice3 marks

Write a function count_lines() that counts the lines that start with "A" or "a" in the text file Hymn.txt and displays the count.

Answer
def count_lines():
    f = open("Hymn.txt", "r")
    c = 0
    for line in f:
        if line[0] in "Aa":
            c += 1
    print(c)
    f.close()
C1.32Practice3 marks

Write a function count_lines() that counts the lines that end with a full stop in the text file Summary.txt and displays the count.

Answer
def count_lines():
    f = open("Summary.txt", "r")
    c = 0
    for line in f:
        if line.strip().endswith("."):
            c += 1
    print(c)
    f.close()
C1.33Practice3 marks

Write a function count_lines() that counts the lines that contain the word "the" in the text file Agenda.txt and displays the count.

Answer
def count_lines():
    f = open("Agenda.txt", "r")
    c = 0
    for line in f:
        if "the" in line.lower().split():
            c += 1
    print(c)
    f.close()
C1.34Practice3 marks

Write a function count_lines() that counts the lines that have more than 30 characters in the text file Log.txt and displays the count.

Answer
def count_lines():
    f = open("Log.txt", "r")
    c = 0
    for line in f:
        if len(line.strip()) > 30:
            c += 1
    print(c)
    f.close()
C1.35Practice3 marks

Write a function count_lines() that counts the lines that have fewer than 6 words in the text file Minutes.txt and displays the count.

Answer
def count_lines():
    f = open("Minutes.txt", "r")
    c = 0
    for line in f:
        if len(line.split()) < 6:
            c += 1
    print(c)
    f.close()
C1.36Practice3 marks

Write a function count_lines() that counts the lines that start with a capital letter in the text file Verse.txt and displays the count.

Answer
def count_lines():
    f = open("Verse.txt", "r")
    c = 0
    for line in f:
        if line[0].isupper():
            c += 1
    print(c)
    f.close()
C1.37Practice3 marks

Write a function show_lines() that displays the lines that contain the word "Python" from the text file Journal.txt.

Answer
def show_lines():
    f = open("Journal.txt", "r")
    for line in f:
        if "Python" in line:
            print(line, end="")
    f.close()
C1.38Practice3 marks

Write a function show_lines() that displays the lines that start with "T" from the text file Travel.txt.

Answer
def show_lines():
    f = open("Travel.txt", "r")
    for line in f:
        if line[0] == "T":
            print(line, end="")
    f.close()
C1.39Practice3 marks

Write a function show_lines() that displays the lines that contain a comma from the text file Science.txt.

Answer
def show_lines():
    f = open("Science.txt", "r")
    for line in f:
        if "," in line:
            print(line, end="")
    f.close()
C1.40Practice3 marks

Write a function show_lines() that displays the lines that have exactly 6 words from the text file Timeline.txt.

Answer
def show_lines():
    f = open("Timeline.txt", "r")
    for line in f:
        if len(line.split()) == 6:
            print(line, end="")
    f.close()
C1.41Practice3 marks

Write a function show_lines() that displays the lines that do not contain the letter "i" from the text file Facts.txt.

Answer
def show_lines():
    f = open("Facts.txt", "r")
    for line in f:
        if "i" not in line:
            print(line, end="")
    f.close()
C1.42Practice3 marks

Write a function show_lines() that displays the lines whose first word has more than 3 letters from the text file Message.txt.

Answer
def show_lines():
    f = open("Message.txt", "r")
    for line in f:
        if len(line.split()[0]) > 3:
            print(line, end="")
    f.close()
C2Stack3 marks · 41 questions
C2.1SQP 2026-273 marks

A list B holds tuples of (book name, price). Write Push_element() to push the books costing more than 250 onto the stack Books, and Pop_element() to pop and display every item and then display "Stack Empty".

Answer
B = [("Machine Learning Basics", 550), ("World Geography", 450),
     ("Wonder World", 140), ("AI Revolution", 750)]
Books = []

def Push_element():
    for item in B:
        if item[1] > 250:
            Books.append(item)

def Pop_element():
    while Books:
        print(Books.pop())
    print("Stack Empty")
C2.2CBSE 20263 marks

Write a program that accepts 10 integers, pushes onto a stack only the three-digit even numbers, and then pops and displays all of them.

Answer
stack = []
for i in range(10):
    n = int(input("Enter number: "))
    if 100 <= n <= 999 and n % 2 == 0:
        stack.append(n)
while stack:
    print(stack.pop(), end=" ")
C2.3CBSE 20253 marks

For a stack ClrStack, write push_Clr(ClrStack, new_Clr) to push a record, pop_Clr(ClrStack) to pop and return the top record or display "Underflow", and isEmpty(ClrStack) to check whether the stack is empty.

Answer
def push_Clr(ClrStack, new_Clr):
    ClrStack.append(new_Clr)

def isEmpty(ClrStack):
    return len(ClrStack) == 0

def pop_Clr(ClrStack):
    if isEmpty(ClrStack):
        print("Underflow")
    else:
        return ClrStack.pop()
C2.4CBSE 20253 marks

Write push_trail(N, myStack) to push the last 5 elements of list N onto myStack, pop_one(myStack) to pop and return one element or return "Stack Underflow", and display_all(myStack) to show all elements or "Empty Stack".

Answer
def push_trail(N, myStack):
    for x in N[-5:]:
        myStack.append(x)

def pop_one(myStack):
    if len(myStack) == 0:
        return "Stack Underflow"
    return myStack.pop()

def display_all(myStack):
    if len(myStack) == 0:
        print("Empty Stack")
    else:
        for x in myStack:
            print(x, end=" ")
C2.5Practice3 marks

A stack FruitStack stores records of the form [name, price]. Write push_fruit(F) to push the record F only if its price is below 100, pop_fruit() to pop a record or display "UNDERFLOW", and display() to show the records from top to bottom or "EMPTY STACK". (Based on the CBSE 2026 stack question.)

Answer
FruitStack = []

def push_fruit(F):
    if F[1] < 100:
        FruitStack.append(F)

def pop_fruit():
    if len(FruitStack) == 0:
        print("UNDERFLOW")
    else:
        print(FruitStack.pop())

def display():
    if len(FruitStack) == 0:
        print("EMPTY STACK")
    else:
        for i in range(len(FruitStack) - 1, -1, -1):
            print(FruitStack[i])
C2.6Practice3 marks

Names is a list of names. Write push_long(Names) to push the names with more than 5 letters onto the stack St, and pop_all() to pop and display all of them.

Answer
St = []

def push_long(Names):
    for n in Names:
        if len(n) > 5:
            St.append(n)

def pop_all():
    while len(St) > 0:
        print(St.pop())
    print("Stack Empty")
C2.7Practice3 marks

A dictionary D stores student names as keys and marks as values. Write push_top(D) to push the names of students scoring more than 75 onto the stack Top, and pop_show() to pop and display the names.

Answer
Top = []

def push_top(D):
    for name in D:
        if D[name] > 75:
            Top.append(name)

def pop_show():
    while Top:
        print(Top.pop(), end=" ")
C2.8Practice3 marks

Write push_even(N) to push the even numbers of list N onto the stack Ev, and pop_even() to pop one number and return it, or return "Underflow" when the stack is empty.

Answer
Ev = []

def push_even(N):
    for x in N:
        if x % 2 == 0:
            Ev.append(x)

def pop_even():
    if len(Ev) == 0:
        return "Underflow"
    return Ev.pop()
C2.9Practice3 marks

A stack Rec stores records of the form [RNo, Name, Marks]. Write push_rec() to input one record and push it, pop_rec() to delete and display the top record, and peek() to display the top record without deleting it.

Answer
Rec = []

def push_rec():
    rno = int(input("Roll no: "))
    name = input("Name: ")
    marks = int(input("Marks: "))
    Rec.append([rno, name, marks])

def pop_rec():
    if len(Rec) == 0:
        print("Underflow")
    else:
        print("Deleted:", Rec.pop())

def peek():
    if len(Rec) == 0:
        print("Stack Empty")
    else:
        print("Top:", Rec[-1])
C2.10Practice3 marks

Write a function reverse(s) that uses a stack to return the reverse of the string s.

Answer
def reverse(s):
    st = []
    for ch in s:
        st.append(ch)          # push every character
    r = ""
    while st:
        r = r + st.pop()       # pop gives the last one first
    return r

print(reverse("PYTHON"))

Output:

NOHTYP
C2.11Practice3 marks

W is a list of words. Write push_vowel(W) to push the words that begin with a vowel onto the stack VS, and show() to display the stack from top to bottom without removing anything.

Answer
VS = []

def push_vowel(W):
    for w in W:
        if w[0] in "aeiouAEIOU":
            VS.append(w)

def show():
    if len(VS) == 0:
        print("Stack Empty")
    else:
        for i in range(len(VS) - 1, -1, -1):
            print(VS[i])
C2.12Practice3 marks

A list N holds numbers, for example [12, 7, 45, 30, 9]. Write push_odd(N) to push the odd numbers onto the stack Stk_odd, and pop_odd() to pop and display all the items and then display "Stack Empty".

Answer
Stk_odd = []

def push_odd(N):
    for x in N:
        if x % 2 != 0:
            Stk_odd.append(x)

def pop_odd():
    while Stk_odd:
        print(Stk_odd.pop(), end=" ")
    print("Stack Empty")
C2.13Practice3 marks

A list N holds numbers, for example [150, 40, 99, 300, 75]. Write push_big(N) to push the numbers greater than 90 onto the stack Stk_big, and pop_big() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_big = []

def push_big(N):
    for x in N:
        if x > 90:
            Stk_big.append(x)

def pop_big():
    if len(Stk_big) == 0:
        print("Underflow")
    else:
        print(Stk_big.pop())
C2.14Practice3 marks

A list N holds numbers, for example [10, 12, 25, 33, 50]. Write push_five(N) to push the numbers divisible by 5 onto the stack Stk_five, and pop_five() to pop and display all the items and then display "Stack Empty".

Answer
Stk_five = []

def push_five(N):
    for x in N:
        if x % 5 == 0:
            Stk_five.append(x)

def pop_five():
    while Stk_five:
        print(Stk_five.pop(), end=" ")
    print("Stack Empty")
C2.15Practice3 marks

A list N holds numbers, for example [5, 23, 108, 64, 9]. Write push_two(N) to push the two-digit numbers onto the stack Stk_two, and pop_two() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_two = []

def push_two(N):
    for x in N:
        if 10 <= x <= 99:
            Stk_two.append(x)

def pop_two():
    if len(Stk_two) == 0:
        print("Underflow")
    else:
        print(Stk_two.pop())
C2.16Practice3 marks

A list N holds numbers, for example [4, -7, 0, -2, 15]. Write push_neg(N) to push the negative numbers onto the stack Stk_neg, and pop_neg() to pop and display all the items and then display "Stack Empty".

Answer
Stk_neg = []

def push_neg(N):
    for x in N:
        if x < 0:
            Stk_neg.append(x)

def pop_neg():
    while Stk_neg:
        print(Stk_neg.pop(), end=" ")
    print("Stack Empty")
C2.17Practice3 marks

A list N holds numbers, for example [9, 14, 21, 25, 30]. Write push_three(N) to push the multiples of 3 onto the stack Stk_three, and pop_three() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_three = []

def push_three(N):
    for x in N:
        if x % 3 == 0:
            Stk_three.append(x)

def pop_three():
    if len(Stk_three) == 0:
        print("Underflow")
    else:
        print(Stk_three.pop())
C2.18Practice3 marks

A list N holds numbers, for example [20, 35, 400, 71, 90]. Write push_zero(N) to push the numbers that end with 0 onto the stack Stk_zero, and pop_zero() to pop and display all the items and then display "Stack Empty".

Answer
Stk_zero = []

def push_zero(N):
    for x in N:
        if x % 10 == 0:
            Stk_zero.append(x)

def pop_zero():
    while Stk_zero:
        print(Stk_zero.pop(), end=" ")
    print("Stack Empty")
C2.19Practice3 marks

A list N holds numbers, for example [65, 12, 48, 90, 33]. Write push_small(N) to push the numbers less than 50 onto the stack Stk_small, and pop_small() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_small = []

def push_small(N):
    for x in N:
        if x < 50:
            Stk_small.append(x)

def pop_small():
    if len(Stk_small) == 0:
        print("Underflow")
    else:
        print(Stk_small.pop())
C2.20Practice3 marks

A list W holds words, for example ["Delhi", "agra", "Pune", "goa"]. Write push_caps(W) to push the words that start with a capital letter onto the stack Stk_caps, and pop_caps() to pop and display all the items and then display "Stack Empty".

Answer
Stk_caps = []

def push_caps(W):
    for w in W:
        if w[0].isupper():
            Stk_caps.append(w)

def pop_caps():
    while Stk_caps:
        print(Stk_caps.pop(), end=" ")
    print("Stack Empty")
C2.21Practice3 marks

A list W holds words, for example ["sun", "planet", "star", "galaxy"]. Write push_long(W) to push the words with 5 or more letters onto the stack Stk_long, and pop_long() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_long = []

def push_long(W):
    for w in W:
        if len(w) >= 5:
            Stk_long.append(w)

def pop_long():
    if len(Stk_long) == 0:
        print("Underflow")
    else:
        print(Stk_long.pop())
C2.22Practice3 marks

A list W holds words, for example ["tables", "chair", "desks", "board"]. Write push_plural(W) to push the words that end with "s" onto the stack Stk_plural, and pop_plural() to pop and display all the items and then display "Stack Empty".

Answer
Stk_plural = []

def push_plural(W):
    for w in W:
        if w.endswith("s"):
            Stk_plural.append(w)

def pop_plural():
    while Stk_plural:
        print(Stk_plural.pop(), end=" ")
    print("Stack Empty")
C2.23Practice3 marks

A list W holds words, for example ["ice", "tea", "oil", "jam", "egg"]. Write push_vowel(W) to push the words that start with a vowel onto the stack Stk_vowel, and pop_vowel() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_vowel = []

def push_vowel(W):
    for w in W:
        if w[0] in "aeiou":
            Stk_vowel.append(w)

def pop_vowel():
    if len(Stk_vowel) == 0:
        print("Underflow")
    else:
        print(Stk_vowel.pop())
C2.24Practice3 marks

A list W holds words, for example ["CPU", "RAM", "Mouse", "USB", "Disk"]. Write push_short(W) to push the words of exactly 3 letters onto the stack Stk_short, and pop_short() to pop and display all the items and then display "Stack Empty".

Answer
Stk_short = []

def push_short(W):
    for w in W:
        if len(w) == 3:
            Stk_short.append(w)

def pop_short():
    while Stk_short:
        print(Stk_short.pop(), end=" ")
    print("Stack Empty")
C2.25Practice3 marks

A list W holds words, for example ["HTML", "Python", "SQL", "Java"]. Write push_upper(W) to push the words written fully in capital letters onto the stack Stk_upper, and pop_upper() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_upper = []

def push_upper(W):
    for w in W:
        if w.isupper():
            Stk_upper.append(w)

def pop_upper():
    if len(Stk_upper) == 0:
        print("Underflow")
    else:
        print(Stk_upper.pop())
C2.26Practice3 marks

A list W holds words, for example ["mango", "kiwi", "banana", "plum"]. Write push_has_a(W) to push the words that contain the letter "a" onto the stack Stk_has_a, and pop_has_a() to pop and display all the items and then display "Stack Empty".

Answer
Stk_has_a = []

def push_has_a(W):
    for w in W:
        if "a" in w:
            Stk_has_a.append(w)

def pop_has_a():
    while Stk_has_a:
        print(Stk_has_a.pop(), end=" ")
    print("Stack Empty")
C2.27Practice3 marks

A dictionary D is given, for example {"Asha": 82, "Ravi": 45, "Tina": 91, "Om": 30}. Write push_marks(D) to push the names of the students who scored 80 or more onto the stack Stk_marks, and pop_marks() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_marks = []

def push_marks(D):
    for k in D:
        if D[k] >= 80:
            Stk_marks.append(k)

def pop_marks():
    if len(Stk_marks) == 0:
        print("Underflow")
    else:
        print(Stk_marks.pop())
C2.28Practice3 marks

A dictionary D is given, for example {"Pen": 10, "Bag": 450, "Shoes": 900, "Cap": 120}. Write push_price(D) to push the names of the items that cost more than 100 onto the stack Stk_price, and pop_price() to pop and display all the items and then display "Stack Empty".

Answer
Stk_price = []

def push_price(D):
    for k in D:
        if D[k] > 100:
            Stk_price.append(k)

def pop_price():
    while Stk_price:
        print(Stk_price.pop(), end=" ")
    print("Stack Empty")
C2.29Practice3 marks

A dictionary D is given, for example {"Neha": 17, "Kabir": 19, "Zara": 16, "Dev": 18}. Write push_age(D) to push the names of the persons aged 18 or more onto the stack Stk_age, and pop_age() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_age = []

def push_age(D):
    for k in D:
        if D[k] >= 18:
            Stk_age.append(k)

def pop_age():
    if len(Stk_age) == 0:
        print("Underflow")
    else:
        print(Stk_age.pop())
C2.30Practice3 marks

A dictionary D is given, for example {"Rice": 0, "Dal": 25, "Oil": 0, "Salt": 40}. Write push_stock(D) to push the names of the items whose stock is 0 onto the stack Stk_stock, and pop_stock() to pop and display all the items and then display "Stack Empty".

Answer
Stk_stock = []

def push_stock(D):
    for k in D:
        if D[k] == 0:
            Stk_stock.append(k)

def pop_stock():
    while Stk_stock:
        print(Stk_stock.pop(), end=" ")
    print("Stack Empty")
C2.31Practice3 marks

A dictionary D is given, for example {"Delhi": 41, "Shimla": 22, "Chennai": 36, "Leh": 12}. Write push_temp(D) to push the names of the cities with temperature below 25 onto the stack Stk_temp, and pop_temp() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_temp = []

def push_temp(D):
    for k in D:
        if D[k] < 25:
            Stk_temp.append(k)

def pop_temp():
    if len(Stk_temp) == 0:
        print("Underflow")
    else:
        print(Stk_temp.pop())
C2.32Practice3 marks

A dictionary D is given, for example {"Rohit": 120, "Gill": 48, "Virat": 95, "Pant": 12}. Write push_runs(D) to push the names of the players who scored 50 or more runs onto the stack Stk_runs, and pop_runs() to pop and display all the items and then display "Stack Empty".

Answer
Stk_runs = []

def push_runs(D):
    for k in D:
        if D[k] >= 50:
            Stk_runs.append(k)

def pop_runs():
    while Stk_runs:
        print(Stk_runs.pop(), end=" ")
    print("Stack Empty")
C2.33Practice3 marks

A dictionary D is given, for example {"Goa": 3702, "Sikkim": 7096, "Kerala": 38863, "Tripura": 10486}. Write push_area(D) to push the names of the states with area below 10000 sq km onto the stack Stk_area, and pop_area() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_area = []

def push_area(D):
    for k in D:
        if D[k] < 10000:
            Stk_area.append(k)

def pop_area():
    if len(Stk_area) == 0:
        print("Underflow")
    else:
        print(Stk_area.pop())
C2.34Practice3 marks

A list Rec holds records, for example [["Wings", 350], ["Roots", 180], ["Atoms", 420]]. Write push_book(Rec) to push the records of books that cost more than 300 onto the stack Stk_book, and pop_book() to pop and display all the items and then display "Stack Empty".

Answer
Stk_book = []

def push_book(Rec):
    for r in Rec:
        if r[1] > 300:
            Stk_book.append(r)

def pop_book():
    while Stk_book:
        print(Stk_book.pop(), end=" ")
    print("Stack Empty")
C2.35Practice3 marks

A list Rec holds records, for example [["Asha", 52000], ["Bilal", 38000], ["Dev", 61000]]. Write push_emp(Rec) to push the records of employees who earn 50000 or more onto the stack Stk_emp, and pop_emp() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_emp = []

def push_emp(Rec):
    for r in Rec:
        if r[1] >= 50000:
            Stk_emp.append(r)

def pop_emp():
    if len(Stk_emp) == 0:
        print("Underflow")
    else:
        print(Stk_emp.pop())
C2.36Practice3 marks

A list Rec holds records, for example [["Jaipur", 280], ["Agra", 230], ["Shimla", 350]]. Write push_city(Rec) to push the records of cities nearer than 300 km onto the stack Stk_city, and pop_city() to pop and display all the items and then display "Stack Empty".

Answer
Stk_city = []

def push_city(Rec):
    for r in Rec:
        if r[1] < 300:
            Stk_city.append(r)

def pop_city():
    while Stk_city:
        print(Stk_city.pop(), end=" ")
    print("Stack Empty")
C2.37Practice3 marks

A list Rec holds records, for example [[1, "Aman", "A"], [2, "Bina", "B"], [3, "Chirag", "A"]]. Write push_stu(Rec) to push the records of students with grade "A" onto the stack Stk_stu, and pop_stu() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_stu = []

def push_stu(Rec):
    for r in Rec:
        if r[2] == "A":
            Stk_stu.append(r)

def pop_stu():
    if len(Stk_stu) == 0:
        print("Underflow")
    else:
        print(Stk_stu.pop())
C2.38Practice3 marks

A list Rec holds records, for example [["Car", 4], ["Bike", 2], ["Auto", 3], ["Cycle", 2]]. Write push_wheel(Rec) to push the records of vehicles with 2 wheels onto the stack Stk_wheel, and pop_wheel() to pop and display all the items and then display "Stack Empty".

Answer
Stk_wheel = []

def push_wheel(Rec):
    for r in Rec:
        if r[1] == 2:
            Stk_wheel.append(r)

def pop_wheel():
    while Stk_wheel:
        print(Stk_wheel.pop(), end=" ")
    print("Stack Empty")
C2.39Practice3 marks

A list Rec holds records, for example [["Nova", 12000], ["Alpha", 18500], ["Lite", 7500]]. Write push_mob(Rec) to push the records of mobiles that cost 12000 or less onto the stack Stk_mob, and pop_mob() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_mob = []

def push_mob(Rec):
    for r in Rec:
        if r[1] <= 12000:
            Stk_mob.append(r)

def pop_mob():
    if len(Stk_mob) == 0:
        print("Underflow")
    else:
        print(Stk_mob.pop())
C2.40Practice3 marks

A list Rec holds records, for example [["Udaan", "Hindi"], ["Sagar", "Tamil"], ["Safar", "Hindi"]]. Write push_film(Rec) to push the records of Hindi films onto the stack Stk_film, and pop_film() to pop and display all the items and then display "Stack Empty".

Answer
Stk_film = []

def push_film(Rec):
    for r in Rec:
        if r[1] == "Hindi":
            Stk_film.append(r)

def pop_film():
    while Stk_film:
        print(Stk_film.pop(), end=" ")
    print("Stack Empty")
C2.41Practice3 marks

A list Rec holds records, for example [["Neha", 45], ["Om", 60], ["Qasim", 72]]. Write push_point(Rec) to push the records of members with more than 50 points onto the stack Stk_point, and pop_point() to pop and display one item, or display "Underflow" when the stack is empty.

Answer
Stk_point = []

def push_point(Rec):
    for r in Rec:
        if r[1] > 50:
            Stk_point.append(r)

def pop_point():
    if len(Stk_point) == 0:
        print("Underflow")
    else:
        print(Stk_point.pop())
C3Write a function or find the output3 marks · 45 questions
C3.1SQP 2026-273 marks

Write a function avg_len() that adds the lengths of all the words of the list my_words and prints the average word length.

Answer
def avg_len():
    my_words = ["computer", "science", "python", "data"]
    total = 0
    for w in my_words:
        total += len(w)
    print("Average word length:", total / len(my_words))

avg_len()

Output:

Average word length: 6.25
C3.2SQP 2026-273 marks

For the tuple pairs = ((2,5), (4,2), (9,8), (12,10)), write a function cnt_even() that counts the pairs (a, b) in which both a and b are even.

Answer
def cnt_even():
    pairs = ((2, 5), (4, 2), (9, 8), (12, 10))
    c = 0
    for a, b in pairs:
        if a % 2 == 0 and b % 2 == 0:
            c += 1
    print(c)

cnt_even()

Output:

2
C3.3SQP 2026-273 marks

Write a function capitalize_words(words) that takes a list of words and returns a new list in which every word starts with a capital letter. (2 marks in the sample paper.)

Answer
def capitalize_words(words):
    new = []
    for w in words:
        new.append(w.capitalize())
    return new

print(capitalize_words(["python", "computer", "science"]))

Output:

['Python', 'Computer', 'Science']
C3.4SQP 2026-273 marks

Write a function sum_positive(list1) that prints the sum of the positive numbers of the list. (2 marks in the sample paper.)

Answer
def sum_positive(list1):
    s = 0
    for num in list1:
        if num > 0:
            s += num
    print(s)

sum_positive([10, -4, 20, 7, -1])

Output:

37
C3.5CBSE 20253 marks

Write the output of the code. (Code reworded from the 2025 paper.)

L1 = []
L2 = []
def split(D):
    for k in D:
        L1.append(k)
        L2.append(D[k])
D = {1: "ONE", 2: "TWO", 3: "THREE"}
split(D)
print(L1)
print(L2)
print(D)
Answer

The function adds the keys to L1 and the values to L2. The dictionary itself does not change.

Output:

[1, 2, 3]
['ONE', 'TWO', 'THREE']
{1: 'ONE', 2: 'TWO', 3: 'THREE'}

Working (step by step)

LineStatementValues after this stepPrinted
1L1 = []L1 = []
2L2 = []L2 = []
7D = {1: "ONE", 2: "TWO", 3: "THREE"}D = {1: 'ONE', 2: 'TWO', 3: 'THREE'}
4for k in D:k = 1
4for k in D:k = 2
4for k in D:k = 3
4for k in D:L1 = [1, 2, 3], L2 = ['ONE', 'TWO', 'THREE']
9print(L1)[1, 2, 3]⏎
10print(L2)['ONE', 'TWO', 'THREE']⏎
11print(D){1: 'ONE', 2: 'TWO', 3: 'THREE'}⏎
C3.6Practice3 marks

Write a function count_upper(s) that returns the number of capital letters in the string s.

Answer
def count_upper(s):
    c = 0
    for ch in s:
        if ch.isupper():
            c += 1
    return c

print(count_upper("Kendriya Vidyalaya Sangathan"))

Output:

3
C3.7Practice3 marks

Write a function odd_squares(L) that returns a new list with the squares of the odd numbers of L.

Answer
def odd_squares(L):
    new = []
    for x in L:
        if x % 2 != 0:
            new.append(x * x)
    return new

print(odd_squares([1, 4, 5, 8, 9]))

Output:

[1, 25, 81]
C3.8Practice3 marks

Write the output of the code.

def modify(s):
    r = ""
    for i in range(len(s)):
        if i % 2 == 0:
            r += s[i].upper()
        else:
            r += str(i)
    return r

print(modify("board"))
Answer

Output:

B1A3D

Working (step by step)

LineStatementValues after this stepPrinted
10print(modify("board"))s = 'board'
2r = ""r = ''
3for i in range(len(s)):i = 0
4if i % 2 == 0:condition is True
5r += s[i].upper()r = 'B'
3for i in range(len(s)):i = 1
4if i % 2 == 0:condition is False
7r += str(i)r = 'B1'
3for i in range(len(s)):i = 2
4if i % 2 == 0:condition is True
5r += s[i].upper()r = 'B1A'
3for i in range(len(s)):i = 3
4if i % 2 == 0:condition is False
7r += str(i)r = 'B1A3'
3for i in range(len(s)):i = 4
4if i % 2 == 0:condition is True

… the same steps continue for the remaining values.

C3.9Practice3 marks

Write the output of the code.

T = (3, 8, 5, 12)
D = {}
for i in range(len(T)):
    if T[i] % 2 == 0:
        D[i] = T[i] // 2
    else:
        D[i] = T[i] * 2
print(D)
Answer

Output:

{0: 6, 1: 4, 2: 10, 3: 6}

Working (step by step)

LineStatementValues after this stepPrinted
1T = (3, 8, 5, 12)T = (3, 8, 5, 12)
2D = {}D = {}
3for i in range(len(T)):i = 0
4if T[i] % 2 == 0:condition is False
7D[i] = T[i] * 2D = {0: 6}
3for i in range(len(T)):i = 1
4if T[i] % 2 == 0:condition is True
5D[i] = T[i] // 2D = {0: 6, 1: 4}
3for i in range(len(T)):i = 2
4if T[i] % 2 == 0:condition is False
7D[i] = T[i] * 2D = {0: 6, 1: 4, 2: 10}
3for i in range(len(T)):i = 3
4if T[i] % 2 == 0:condition is True
5D[i] = T[i] // 2D = {0: 6, 1: 4, 2: 10, 3: 6}
3for i in range(len(T)):loop ends (no more values)
8print(D){0: 6, 1: 4, 2: 10, 3: 6}⏎
C3.10Practice3 marks

Write a function is_prime(n) that returns True if n is a prime number, otherwise False.

Answer
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, n):
        if n % i == 0:
            return False
    return True

print(is_prime(17), is_prime(21))

Output:

True False
C3.11Practice3 marks

Write a function longest(sentence) that returns the longest word of a sentence.

Answer
def longest(sentence):
    big = ""
    for w in sentence.split():
        if len(w) > len(big):
            big = w
    return big

print(longest("Practice makes a student perfect"))

Output:

Practice
C3.12Practice3 marks

Write a function vowel_count(s) that returns a dictionary showing how many times each vowel occurs in s.

Answer
def vowel_count(s):
    D = {}
    for ch in s.lower():
        if ch in "aeiou":
            D[ch] = D.get(ch, 0) + 1
    return D

print(vowel_count("Education"))

Output:

{'e': 1, 'u': 1, 'a': 1, 'i': 1, 'o': 1}
C3.13Practice3 marks

Write a function total(L) that returns the sum of the elements of a list without using sum().

Answer
def total(L):
    s = 0
    for x in L:
        s += x
    return s

print(total([4, 8, 15]))

Output:

27
C3.14Practice3 marks

Write a function count_vowels(s) that returns the number of vowels in a string.

Answer
def count_vowels(s):
    c = 0
    for ch in s:
        if ch in "aeiouAEIOU":
            c += 1
    return c

print(count_vowels("Computer Science"))

Output:

6
C3.15Practice3 marks

Write a function reverse_words(s) that returns the sentence with its words in reverse order.

Answer
def reverse_words(s):
    words = s.split()
    words.reverse()
    return " ".join(words)

print(reverse_words("Python is easy"))

Output:

easy is Python
C3.16Practice3 marks

Write a function evens(L) that returns a list of the even numbers of L.

Answer
def evens(L):
    new = []
    for x in L:
        if x % 2 == 0:
            new.append(x)
    return new

print(evens([3, 8, 12, 5, 6]))

Output:

[8, 12, 6]
C3.17Practice3 marks

Write a function largest(a, b, c) that returns the largest of three numbers without using max().

Answer
def largest(a, b, c):
    big = a
    if b > big:
        big = b
    if c > big:
        big = c
    return big

print(largest(14, 29, 8))

Output:

29
C3.18Practice3 marks

Write a function fact(n) that returns the factorial of n.

Answer
def fact(n):
    f = 1
    for i in range(1, n + 1):
        f *= i
    return f

print(fact(6))

Output:

720
C3.19Practice3 marks

Write a function table(n) that prints the first five multiples of n on one line.

Answer
def table(n):
    for i in range(1, 6):
        print(n * i, end=" ")

table(7)

Output:

7 14 21 28 35 
C3.20Practice3 marks

Write a function count_word(s, w) that returns how many times the word w occurs in the sentence s.

Answer
def count_word(s, w):
    c = 0
    for x in s.split():
        if x == w:
            c += 1
    return c

print(count_word("the cat and the hat", "the"))

Output:

2
C3.21Practice3 marks

Write a function swap_case(s) that changes capital letters to small and small letters to capital, without using swapcase().

Answer
def swap_case(s):
    r = ""
    for ch in s:
        if ch.isupper():
            r += ch.lower()
        else:
            r += ch.upper()
    return r

print(swap_case("Kendriya"))

Output:

kENDRIYA
C3.22Practice3 marks

Write a function second_largest(L) that returns the second largest number of a list of different numbers.

Answer
def second_largest(L):
    M = sorted(L)
    return M[-2]

print(second_largest([14, 67, 29, 51]))

Output:

51
C3.23Practice3 marks

Write a function remove_dup(L) that returns a list without repeated elements, keeping the first occurrence.

Answer
def remove_dup(L):
    new = []
    for x in L:
        if x not in new:
            new.append(x)
    return new

print(remove_dup([2, 5, 2, 8, 5]))

Output:

[2, 5, 8]
C3.24Practice3 marks

Write a function sum_digits(n) that returns the sum of the digits of a number.

Answer
def sum_digits(n):
    s = 0
    while n > 0:
        s += n % 10
        n //= 10
    return s

print(sum_digits(4725))

Output:

18
C3.25Practice3 marks

Write a function fib(n) that prints the first n numbers of the Fibonacci series.

Answer
def fib(n):
    a, b = 0, 1
    for i in range(n):
        print(a, end=" ")
        a, b = b, a + b

fib(7)

Output:

0 1 1 2 3 5 8 
C3.26Practice3 marks

Write a function count_range(L, lo, hi) that returns how many numbers of L lie from lo to hi (both included).

Answer
def count_range(L, lo, hi):
    c = 0
    for x in L:
        if lo <= x <= hi:
            c += 1
    return c

print(count_range([12, 45, 30, 8, 27], 10, 30))

Output:

3
C3.27Practice3 marks

Write a function invert(D) that returns a new dictionary in which the keys and values of D are exchanged.

Answer
def invert(D):
    new = {}
    for k in D:
        new[D[k]] = k
    return new

print(invert({"a": 1, "b": 2}))

Output:

{1: 'a', 2: 'b'}
C3.28Practice3 marks

Write a function initials(name) that returns the first letters of all the words of a name in capitals.

Answer
def initials(name):
    r = ""
    for w in name.split():
        r += w[0].upper()
    return r

print(initials("kendriya vidyalaya sangathan"))

Output:

KVS
C3.29Practice3 marks

Write a function average(T) that returns the average of the numbers of a tuple.

Answer
def average(T):
    s = 0
    for x in T:
        s += x
    return s / len(T)

print(average((10, 20, 60)))

Output:

30.0
C3.30Practice3 marks

Write a function power(b, e) that returns b raised to e using a loop.

Answer
def power(b, e):
    p = 1
    for i in range(e):
        p *= b
    return p

print(power(2, 10))

Output:

1024
C3.31Practice3 marks

Write a function positions(L, x) that returns a list of the indexes at which x occurs in L.

Answer
def positions(L, x):
    pos = []
    for i in range(len(L)):
        if L[i] == x:
            pos.append(i)
    return pos

print(positions([5, 3, 5, 9, 5], 5))

Output:

[0, 2, 4]
C3.32Practice3 marks

Write a function hcf(a, b) that returns the highest common factor of two numbers.

Answer
def hcf(a, b):
    h = 1
    for i in range(1, min(a, b) + 1):
        if a % i == 0 and b % i == 0:
            h = i
    return h

print(hcf(36, 48))

Output:

12
C3.33Practice3 marks

Write a function count_types(s) that returns two values: the number of letters and the number of digits in s.

Answer
def count_types(s):
    a = d = 0
    for ch in s:
        if ch.isalpha():
            a += 1
        elif ch.isdigit():
            d += 1
    return a, d

print(count_types("Exam2027"))

Output:

(4, 4)
C3.34Practice3 marks

A dictionary D has names as keys and marks as values. Write a function above_avg(D) that returns a list of the names who scored more than the average.

Answer
def above_avg(D):
    avg = sum(D.values()) / len(D)
    names = []
    for k in D:
        if D[k] > avg:
            names.append(k)
    return names

print(above_avg({"Asha": 90, "Ravi": 60, "Tina": 75}))

Output:

['Asha']
C3.35Practice3 marks

Write a function shift_left(L) that moves the first element of the list to the end.

Answer
def shift_left(L):
    x = L.pop(0)
    L.append(x)

A = [1, 2, 3, 4]
shift_left(A)
print(A)

Output:

[2, 3, 4, 1]
C3.36Practice3 marks

Write a function to_dict(K, V) that makes a dictionary from a list of keys and a list of values.

Answer
def to_dict(K, V):
    D = {}
    for i in range(len(K)):
        D[K[i]] = V[i]
    return D

print(to_dict(["x", "y"], [10, 20]))

Output:

{'x': 10, 'y': 20}
C3.37Practice3 marks

Write a function grade(m) that returns "A" for marks 75 or more, "B" for 50 or more, otherwise "C".

Answer
def grade(m):
    if m >= 75:
        return "A"
    elif m >= 50:
        return "B"
    else:
        return "C"

print(grade(82), grade(64), grade(31))

Output:

A B C
C3.38Practice3 marks

Write a function min_max(L) that returns both the smallest and the largest number of a list.

Answer
def min_max(L):
    lo = hi = L[0]
    for x in L:
        if x < lo:
            lo = x
        if x > hi:
            hi = x
    return lo, hi

print(min_max([14, 3, 27, 9]))

Output:

(3, 27)
C3.39Practice3 marks

Write a function interest(p, r=5, t=1) that returns the simple interest. Call it with one, two and three arguments.

Answer
def interest(p, r=5, t=1):
    return p * r * t / 100

print(interest(1000), interest(1000, 8), interest(1000, 8, 2))

Output:

50.0 80.0 160.0
C3.40Practice3 marks

Write a function squares(n) that returns a dictionary of the numbers 1 to n with their squares.

Answer
def squares(n):
    D = {}
    for i in range(1, n + 1):
        D[i] = i * i
    return D

print(squares(4))

Output:

{1: 1, 2: 4, 3: 9, 4: 16}
C3.41Practice3 marks

Write a function is_leap(y) that returns True if y is a leap year.

Answer
def is_leap(y):
    if y % 400 == 0:
        return True
    if y % 100 == 0:
        return False
    return y % 4 == 0

print(is_leap(2028), is_leap(2100), is_leap(2000))

Output:

True False True
C3.42Practice3 marks

Write a function count_long(L, n) that returns how many strings of the list L have more than n characters.

Answer
def count_long(L, n):
    c = 0
    for s in L:
        if len(s) > n:
            c += 1
    return c

print(count_long(["sun", "planet", "star", "galaxy"], 4))

Output:

2
C3.43Practice3 marks

Write a function count_even(T) that returns how many numbers of a tuple are even.

Answer
def count_even(T):
    c = 0
    for x in T:
        if x % 2 == 0:
            c += 1
    return c

print(count_even((4, 7, 10, 13, 16)))

Output:

3
C3.44Practice3 marks

Write a function first_last(s) that returns a string made of the first and the last character of every word of s.

Answer
def first_last(s):
    r = ""
    for w in s.split():
        r += w[0] + w[-1]
    return r

print(first_last("Kendriya Vidyalaya Delhi"))

Output:

KaVaDi
C3.45Practice3 marks

Write a function multiples(n, k) that returns a list of the first k multiples of n.

Answer
def multiples(n, k):
    L = []
    for i in range(1, k + 1):
        L.append(n * i)
    return L

print(multiples(6, 4))

Output:

[6, 12, 18, 24]

Section D · 4 marks each

D1SQL queries on one table4 marks · 40 questions
D1.1SQP 2026-274 marks

Table TECH_EVENT_REG is given below. Write queries to:

  1. Show the events that have more than one participant
  2. Show every event name only once
  3. Show the participants whose name contains "an"
  4. Show all records in descending order of participant name.

Table: TECH_EVENT_REG

reg_idparticipant_nameevent_namegradereg_fee
501AaravHackathon11200
502RiyaRoboRace10150
503KrishWebDev Challenge12250
504NavyaHackathon11200
505SamairaCodeSprint9100
506RohanRoboRace10150
Answer
SELECT event_name, COUNT(*) FROM TECH_EVENT_REG
  GROUP BY event_name HAVING COUNT(*) > 1;
SELECT DISTINCT event_name FROM TECH_EVENT_REG;
SELECT * FROM TECH_EVENT_REG WHERE participant_name LIKE '%an%';
SELECT * FROM TECH_EVENT_REG ORDER BY participant_name DESC;
D1.2Practice4 marks

Write the output of these queries on the table TECH_EVENT_REG of the sample paper.

Table: TECH_EVENT_REG

reg_idparticipant_nameevent_namegradereg_fee
501AaravHackathon11200
502RiyaRoboRace10150
503KrishWebDev Challenge12250
504NavyaHackathon11200
505SamairaCodeSprint9100
506RohanRoboRace10150
SELECT participant_name, event_name FROM TECH_EVENT_REG WHERE grade = 11;
SELECT event_name, COUNT(*) FROM TECH_EVENT_REG GROUP BY event_name;
SELECT participant_name FROM TECH_EVENT_REG WHERE reg_fee > 200;
SELECT MAX(reg_fee) FROM TECH_EVENT_REG WHERE grade = 10;
Answer
(i)
participant_nameevent_name
AaravHackathon
NavyaHackathon

Explanation: WHERE keeps only the rows where grade is 11: 2 of the 6 rows match (Aarav, Navya).

(ii)
event_nameCOUNT(*)
CodeSprint1
Hackathon2
RoboRace2
WebDev Challenge1

Explanation: GROUP BY event_name makes 4 groups (CodeSprint, Hackathon, RoboRace, WebDev Challenge); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
participant_name
Krish

Explanation: WHERE keeps only the rows where reg_fee is more than 200: 1 of the 6 rows matches (Krish).

(iv)
MAX(reg_fee)
150

Explanation: WHERE keeps only the rows where grade is 10: 2 of the 6 rows match (Riya, Rohan). MAX gives the largest value of the matching rows.

D1.3CBSE 20264 marks

Table STOCK (Code, Type, Qty, Price ...). Write queries to:

  1. Show the highest price in each Type
  2. Increase the price of Type 'F' items by 0.5
  3. Show the total value of the stock (Qty x Price)
  4. Show the items whose Code begins with 'A'.

Table: STOCK

CodeTypeQtyPrice
Columns only. The rows are given in the question paper.
Answer
SELECT Type, MAX(Price) FROM STOCK GROUP BY Type;
UPDATE STOCK SET Price = Price + 0.5 WHERE Type = 'F';
SELECT SUM(Qty * Price) FROM STOCK;
SELECT * FROM STOCK WHERE Code LIKE 'A%';
D1.4CBSE 20254 marks

Table WORKER (WNAME, WAGE, HOURS, TYPE, SITEID ...). Write queries to:

  1. Show the name and wage of workers earning 800 to 1500
  2. Show the workers with no site allotted
  3. Show name, wage and hours of 'Skilled' workers
  4. Set the wage of 'Semiskilled' workers to 1200.

Table: WORKER

WNAMEWAGEHOURSTYPESITEID
Columns only. The rows are given in the question paper.
Answer
SELECT WNAME, WAGE FROM WORKER WHERE WAGE BETWEEN 800 AND 1500;
SELECT * FROM WORKER WHERE SITEID IS NULL;
SELECT WNAME, WAGE, HOURS FROM WORKER WHERE TYPE = 'Skilled';
UPDATE WORKER SET WAGE = 1200 WHERE TYPE = 'Semiskilled';
D1.5Practice4 marks

Table STUDENT (RNo, Name, Stream, Marks, City). Write queries to:

  1. Show the name and marks of Science students who scored more than 80
  2. Show the number of students in each stream
  3. Add 5 marks to the students of Delhi
  4. Show the names that end with 'a'.

Table: STUDENT

RNoNameStreamMarksCity
Columns only. The rows are given in the question paper.
Answer
SELECT Name, Marks FROM STUDENT WHERE Stream = 'Science' AND Marks > 80;
SELECT Stream, COUNT(*) FROM STUDENT GROUP BY Stream;
UPDATE STUDENT SET Marks = Marks + 5 WHERE City = 'Delhi';
SELECT Name FROM STUDENT WHERE Name LIKE '%a';
D1.6Practice4 marks

Table EMPLOYEE (ENo, EName, Dept, Salary, DOJ). Write queries to:

  1. Show the average salary of each department
  2. Show the employees who joined after 1 January 2020
  3. Show the different departments
  4. Delete the employees whose salary has not been entered.

Table: EMPLOYEE

ENoENameDeptSalaryDOJ
Columns only. The rows are given in the question paper.
Answer
SELECT Dept, AVG(Salary) FROM EMPLOYEE GROUP BY Dept;
SELECT * FROM EMPLOYEE WHERE DOJ > '2020-01-01';
SELECT DISTINCT Dept FROM EMPLOYEE;
DELETE FROM EMPLOYEE WHERE Salary IS NULL;
D1.7Practice4 marks

Table BOOK (BNo, Title, Author, Price, Qty). Write queries to:

  1. Show title and price of books costing 200 to 500, cheapest first
  2. Show the total number of copies
  3. Show the authors who have more than one book
  4. Increase the price by 10% for the books of author 'R. Sharma'.

Table: BOOK

BNoTitleAuthorPriceQty
Columns only. The rows are given in the question paper.
Answer
SELECT Title, Price FROM BOOK WHERE Price BETWEEN 200 AND 500 ORDER BY Price;
SELECT SUM(Qty) FROM BOOK;
SELECT Author, COUNT(*) FROM BOOK GROUP BY Author HAVING COUNT(*) > 1;
UPDATE BOOK SET Price = Price * 1.10 WHERE Author = 'R. Sharma';
D1.8Practice4 marks

Table PRODUCT (PID, PName, Company, Price, Stock). Write queries to:

  1. Show the companies that have more than 2 products
  2. Show the products whose name has 'a' as the second letter
  3. Show the lowest and the highest price
  4. Show the products whose stock is 0, 5 or 10.

Table: PRODUCT

PIDPNameCompanyPriceStock
Columns only. The rows are given in the question paper.
Answer
SELECT Company, COUNT(*) FROM PRODUCT GROUP BY Company HAVING COUNT(*) > 2;
SELECT * FROM PRODUCT WHERE PName LIKE '_a%';
SELECT MIN(Price), MAX(Price) FROM PRODUCT;
SELECT * FROM PRODUCT WHERE Stock IN (0, 5, 10);
D1.9Practice4 marks

Table DOCTOR (DID, DName, Dept, Fee, Experience). Write queries to:

  1. Show the doctors of 'Cardiology' or 'ENT' in order of name
  2. Show the highest fee in each department
  3. Show name and experience of doctors with more than 10 years of experience and fee below 800
  4. Reduce the fee by 100 for doctors with less than 3 years of experience.

Table: DOCTOR

DIDDNameDeptFeeExperience
Columns only. The rows are given in the question paper.
Answer
SELECT * FROM DOCTOR WHERE Dept IN ('Cardiology', 'ENT') ORDER BY DName;
SELECT Dept, MAX(Fee) FROM DOCTOR GROUP BY Dept;
SELECT DName, Experience FROM DOCTOR WHERE Experience > 10 AND Fee < 800;
UPDATE DOCTOR SET Fee = Fee - 100 WHERE Experience < 3;
D1.10Practice4 marks

Table TRAIN (TNo, TName, Source, Dest, Fare). Write queries to:

  1. Show the trains starting from 'Delhi', costliest first
  2. Show the number of trains reaching each destination
  3. Show the trains whose name contains 'Express'
  4. Show the average fare of the trains starting from 'Delhi'.

Table: TRAIN

TNoTNameSourceDestFare
Columns only. The rows are given in the question paper.
Answer
SELECT * FROM TRAIN WHERE Source = 'Delhi' ORDER BY Fare DESC;
SELECT Dest, COUNT(*) FROM TRAIN GROUP BY Dest;
SELECT * FROM TRAIN WHERE TName LIKE '%Express%';
SELECT AVG(Fare) FROM TRAIN WHERE Source = 'Delhi';
D1.11Practice4 marks

Write SQL queries for the following, based on the table TEACHER.

Table: TEACHER

TNoTNameSubjectSalaryCity
1SunitaMaths52000Delhi
2RakeshPhysics61000Agra
3SeemaMaths48000Delhi
4ImranEnglish45000Pune
5SureshPhysics58000Delhi
6AnitaEnglish39000Agra
  1. Show the TName and Salary of the teachers whose City is 'Delhi'.
  2. Show the number of teachers in each Subject.
  3. Show the teachers whose Salary is from 45000 to 58000.
  4. Increase the Salary by 2000 for the teachers whose City is 'Delhi'.
Answer
(i)
SELECT TName, Salary FROM TEACHER WHERE City = 'Delhi';
TNameSalary
Sunita52000
Seema48000
Suresh58000

Explanation: WHERE keeps only the rows where City is 'Delhi': 3 of the 6 rows match (Sunita, Seema, Suresh).

(ii)
SELECT Subject, COUNT(*) FROM TEACHER GROUP BY Subject;
SubjectCOUNT(*)
English2
Maths2
Physics2

Explanation: GROUP BY Subject makes 3 groups (English, Maths, Physics); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
SELECT * FROM TEACHER WHERE Salary BETWEEN 45000 AND 58000;
TNoTNameSubjectSalaryCity
1SunitaMaths52000Delhi
3SeemaMaths48000Delhi
4ImranEnglish45000Pune
5SureshPhysics58000Delhi

Explanation: WHERE keeps only the rows where Salary is from 45000 to 58000 (both included): 4 of the 6 rows match (Sunita, Seema, Imran, Suresh).

(iv)
UPDATE TEACHER SET Salary = Salary + 2000 WHERE City = 'Delhi';

3 rows changed.

Explanation: SET Salary = Salary + 2000 changes the value; WHERE limits the change to the rows where City is 'Delhi': 3 rows changed.

D1.12Practice4 marks

Write SQL queries for the following, based on the table TEACHER.

Table: TEACHER

TNoTNameSubjectSalaryCity
1SunitaMaths52000Delhi
2RakeshPhysics61000Agra
3SeemaMaths48000Delhi
4ImranEnglish45000Pune
5SureshPhysics58000Delhi
6AnitaEnglish39000Agra
  1. Show all the teachers in descending order of Salary.
  2. Show the highest and the lowest Salary.
  3. Show the TName of the teachers whose TName starts with S.
  4. Delete the teachers whose Salary is less than 45000.
Answer
(i)
SELECT * FROM TEACHER ORDER BY Salary DESC;
TNoTNameSubjectSalaryCity
2RakeshPhysics61000Agra
5SureshPhysics58000Delhi
1SunitaMaths52000Delhi
3SeemaMaths48000Delhi
4ImranEnglish45000Pune
6AnitaEnglish39000Agra

Explanation: ORDER BY Salary arranges the result in descending (largest first) order.

(ii)
SELECT MAX(Salary), MIN(Salary) FROM TEACHER;
MAX(Salary)MIN(Salary)
6100039000

Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.

(iii)
SELECT TName FROM TEACHER WHERE TName LIKE 'S%';
TName
Sunita
Seema
Suresh

Explanation: WHERE keeps only the rows where TName matches the pattern 'S%': 3 of the 6 rows match (Sunita, Seema, Suresh). 'S%' means the value starts with 'S'.

(iv)
DELETE FROM TEACHER WHERE Salary < 45000;

1 row changed.

Explanation: WHERE picks the rows where Salary is less than 45000: 1 row is deleted; the table and the other rows remain.

D1.13Practice4 marks

Write SQL queries for the following, based on the table TEACHER.

Table: TEACHER

TNoTNameSubjectSalaryCity
1SunitaMaths52000Delhi
2RakeshPhysics61000Agra
3SeemaMaths48000Delhi
4ImranEnglish45000Pune
5SureshPhysics58000Delhi
6AnitaEnglish39000Agra
  1. Show the different values of Subject.
  2. Show each Subject that has more than one teacher, with the count.
  3. Show the TName of the teachers whose City is 'Delhi' or 'Agra'.
  4. Show the total Salary of the teachers whose City is 'Agra'.
Answer
(i)
SELECT DISTINCT Subject FROM TEACHER;
Subject
Maths
Physics
English

Explanation: DISTINCT removes the repeated rows from the result of all the rows.

(ii)
SELECT Subject, COUNT(*) FROM TEACHER GROUP BY Subject HAVING COUNT(*) > 1;
SubjectCOUNT(*)
English2
Maths2
Physics2

Explanation: GROUP BY Subject makes 3 groups (English, Maths, Physics); the aggregate function is worked out separately for each group. HAVING then keeps only the groups where COUNT(*) is more than 1. COUNT(*) counts the rows.

(iii)
SELECT TName FROM TEACHER WHERE City IN ('Delhi', 'Agra');
TName
Sunita
Rakesh
Seema
Suresh
Anita

Explanation: WHERE keeps only the rows where City is one of ('Delhi', 'Agra'): 5 of the 6 rows match (Sunita, Rakesh, Seema, Suresh, Anita).

(iv)
SELECT SUM(Salary) FROM TEACHER WHERE City = 'Agra';
SUM(Salary)
100000

Explanation: WHERE keeps only the rows where City is 'Agra': 2 of the 6 rows match (Rakesh, Anita). SUM adds the values of the matching rows.

D1.14Practice4 marks

Write SQL queries for the following, based on the table MOVIE.

Table: MOVIE

MNoTitleLanguageRatingTickets
1UdaanHindi8450
2SagarTamil7300
3SafarHindi6520
4NadiBengali9210
5SapnaTamil8390
6DhoopHindi5150
  1. Show the Title and Tickets of the movies whose Language is 'Hindi'.
  2. Show the number of movies in each Language.
  3. Show the movies whose Tickets is from 200 to 400.
  4. Increase the Tickets by 50 for the movies whose Language is 'Hindi'.
Answer
(i)
SELECT Title, Tickets FROM MOVIE WHERE Language = 'Hindi';
TitleTickets
Udaan450
Safar520
Dhoop150

Explanation: WHERE keeps only the rows where Language is 'Hindi': 3 of the 6 rows match (Udaan, Safar, Dhoop).

(ii)
SELECT Language, COUNT(*) FROM MOVIE GROUP BY Language;
LanguageCOUNT(*)
Bengali1
Hindi3
Tamil2

Explanation: GROUP BY Language makes 3 groups (Bengali, Hindi, Tamil); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
SELECT * FROM MOVIE WHERE Tickets BETWEEN 200 AND 400;
MNoTitleLanguageRatingTickets
2SagarTamil7300
4NadiBengali9210
5SapnaTamil8390

Explanation: WHERE keeps only the rows where Tickets is from 200 to 400 (both included): 3 of the 6 rows match (Sagar, Nadi, Sapna).

(iv)
UPDATE MOVIE SET Tickets = Tickets + 50 WHERE Language = 'Hindi';

3 rows changed.

Explanation: SET Tickets = Tickets + 50 changes the value; WHERE limits the change to the rows where Language is 'Hindi': 3 rows changed.

D1.15Practice4 marks

Write SQL queries for the following, based on the table MOVIE.

Table: MOVIE

MNoTitleLanguageRatingTickets
1UdaanHindi8450
2SagarTamil7300
3SafarHindi6520
4NadiBengali9210
5SapnaTamil8390
6DhoopHindi5150
  1. Show all the movies in descending order of Tickets.
  2. Show the highest and the lowest Tickets.
  3. Show the Title of the movies whose Title ends with a.
  4. Delete the movies whose Tickets is less than 250.
Answer
(i)
SELECT * FROM MOVIE ORDER BY Tickets DESC;
MNoTitleLanguageRatingTickets
3SafarHindi6520
1UdaanHindi8450
5SapnaTamil8390
2SagarTamil7300
4NadiBengali9210
6DhoopHindi5150

Explanation: ORDER BY Tickets arranges the result in descending (largest first) order.

(ii)
SELECT MAX(Tickets), MIN(Tickets) FROM MOVIE;
MAX(Tickets)MIN(Tickets)
520150

Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.

(iii)
SELECT Title FROM MOVIE WHERE Title LIKE '%a';
Title
Sapna

Explanation: WHERE keeps only the rows where Title matches the pattern '%a': 1 of the 6 rows matches (Sapna). '%a' means the value ends with 'a'.

(iv)
DELETE FROM MOVIE WHERE Tickets < 250;

2 rows changed.

Explanation: WHERE picks the rows where Tickets is less than 250: 2 rows are deleted; the table and the other rows remain.

D1.16Practice4 marks

Write SQL queries for the following, based on the table MOVIE.

Table: MOVIE

MNoTitleLanguageRatingTickets
1UdaanHindi8450
2SagarTamil7300
3SafarHindi6520
4NadiBengali9210
5SapnaTamil8390
6DhoopHindi5150
  1. Show the different values of Language.
  2. Show each Language that has more than one movie, with the count.
  3. Show the Title of the movies whose Language is 'Hindi' or 'Tamil'.
  4. Show the total Tickets of the movies whose Language is 'Tamil'.
Answer
(i)
SELECT DISTINCT Language FROM MOVIE;
Language
Hindi
Tamil
Bengali

Explanation: DISTINCT removes the repeated rows from the result of all the rows.

(ii)
SELECT Language, COUNT(*) FROM MOVIE GROUP BY Language HAVING COUNT(*) > 1;
LanguageCOUNT(*)
Hindi3
Tamil2

Explanation: GROUP BY Language makes 3 groups (Bengali, Hindi, Tamil); the aggregate function is worked out separately for each group. HAVING then keeps only the groups where COUNT(*) is more than 1. COUNT(*) counts the rows.

(iii)
SELECT Title FROM MOVIE WHERE Language IN ('Hindi', 'Tamil');
Title
Udaan
Sagar
Safar
Sapna
Dhoop

Explanation: WHERE keeps only the rows where Language is one of ('Hindi', 'Tamil'): 5 of the 6 rows match (Udaan, Sagar, Safar, Sapna, Dhoop).

(iv)
SELECT SUM(Tickets) FROM MOVIE WHERE Language = 'Tamil';
SUM(Tickets)
690

Explanation: WHERE keeps only the rows where Language is 'Tamil': 2 of the 6 rows match (Sagar, Sapna). SUM adds the values of the matching rows.

D1.17Practice4 marks

Write SQL queries for the following, based on the table FLIGHT.

Table: FLIGHT

FNoAirlineSourceSeatsFare
F101SkyJetDelhi1805200
F102AirWingMumbai1504800
F103SkyJetDelhi2006100
F104CloudAirKolkata1203900
F105AirWingDelhi1605500
F106CloudAirMumbai1404200
  1. Show the FNo and Fare of the flights whose Source is 'Delhi'.
  2. Show the number of flights in each Airline.
  3. Show the flights whose Fare is from 4000 to 5500.
  4. Increase the Fare by 300 for the flights whose Source is 'Delhi'.
Answer
(i)
SELECT FNo, Fare FROM FLIGHT WHERE Source = 'Delhi';
FNoFare
F1015200
F1036100
F1055500

Explanation: WHERE keeps only the rows where Source is 'Delhi': 3 of the 6 rows match (F101, F103, F105).

(ii)
SELECT Airline, COUNT(*) FROM FLIGHT GROUP BY Airline;
AirlineCOUNT(*)
AirWing2
CloudAir2
SkyJet2

Explanation: GROUP BY Airline makes 3 groups (AirWing, CloudAir, SkyJet); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
SELECT * FROM FLIGHT WHERE Fare BETWEEN 4000 AND 5500;
FNoAirlineSourceSeatsFare
F101SkyJetDelhi1805200
F102AirWingMumbai1504800
F105AirWingDelhi1605500
F106CloudAirMumbai1404200

Explanation: WHERE keeps only the rows where Fare is from 4000 to 5500 (both included): 4 of the 6 rows match (F101, F102, F105, F106).

(iv)
UPDATE FLIGHT SET Fare = Fare + 300 WHERE Source = 'Delhi';

3 rows changed.

Explanation: SET Fare = Fare + 300 changes the value; WHERE limits the change to the rows where Source is 'Delhi': 3 rows changed.

D1.18Practice4 marks

Write SQL queries for the following, based on the table FLIGHT.

Table: FLIGHT

FNoAirlineSourceSeatsFare
F101SkyJetDelhi1805200
F102AirWingMumbai1504800
F103SkyJetDelhi2006100
F104CloudAirKolkata1203900
F105AirWingDelhi1605500
F106CloudAirMumbai1404200
  1. Show all the flights in descending order of Fare.
  2. Show the highest and the lowest Fare.
  3. Show the FNo of the flights whose Airline contains Air.
  4. Delete the flights whose Fare is less than 4500.
Answer
(i)
SELECT * FROM FLIGHT ORDER BY Fare DESC;
FNoAirlineSourceSeatsFare
F103SkyJetDelhi2006100
F105AirWingDelhi1605500
F101SkyJetDelhi1805200
F102AirWingMumbai1504800
F106CloudAirMumbai1404200
F104CloudAirKolkata1203900

Explanation: ORDER BY Fare arranges the result in descending (largest first) order.

(ii)
SELECT MAX(Fare), MIN(Fare) FROM FLIGHT;
MAX(Fare)MIN(Fare)
61003900

Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.

(iii)
SELECT FNo FROM FLIGHT WHERE Airline LIKE '%Air%';
FNo
F102
F104
F105
F106

Explanation: WHERE keeps only the rows where Airline matches the pattern '%Air%': 4 of the 6 rows match (F102, F104, F105, F106). '%Air%' means the value contains 'Air'.

(iv)
DELETE FROM FLIGHT WHERE Fare < 4500;

2 rows changed.

Explanation: WHERE picks the rows where Fare is less than 4500: 2 rows are deleted; the table and the other rows remain.

D1.19Practice4 marks

Write SQL queries for the following, based on the table FLIGHT.

Table: FLIGHT

FNoAirlineSourceSeatsFare
F101SkyJetDelhi1805200
F102AirWingMumbai1504800
F103SkyJetDelhi2006100
F104CloudAirKolkata1203900
F105AirWingDelhi1605500
F106CloudAirMumbai1404200
  1. Show the different values of Airline.
  2. Show each Airline that has more than one flight, with the count.
  3. Show the FNo of the flights whose Source is 'Delhi' or 'Mumbai'.
  4. Show the total Fare of the flights whose Source is 'Mumbai'.
Answer
(i)
SELECT DISTINCT Airline FROM FLIGHT;
Airline
SkyJet
AirWing
CloudAir

Explanation: DISTINCT removes the repeated rows from the result of all the rows.

(ii)
SELECT Airline, COUNT(*) FROM FLIGHT GROUP BY Airline HAVING COUNT(*) > 1;
AirlineCOUNT(*)
AirWing2
CloudAir2
SkyJet2

Explanation: GROUP BY Airline makes 3 groups (AirWing, CloudAir, SkyJet); the aggregate function is worked out separately for each group. HAVING then keeps only the groups where COUNT(*) is more than 1. COUNT(*) counts the rows.

(iii)
SELECT FNo FROM FLIGHT WHERE Source IN ('Delhi', 'Mumbai');
FNo
F101
F102
F103
F105
F106

Explanation: WHERE keeps only the rows where Source is one of ('Delhi', 'Mumbai'): 5 of the 6 rows match (F101, F102, F103, F105, F106).

(iv)
SELECT SUM(Fare) FROM FLIGHT WHERE Source = 'Mumbai';
SUM(Fare)
9000

Explanation: WHERE keeps only the rows where Source is 'Mumbai': 2 of the 6 rows match (F102, F106). SUM adds the values of the matching rows.

D1.20Practice4 marks

Write SQL queries for the following, based on the table MOBILE.

Table: MOBILE

MIDModelBrandPriceStock
1Nova 5Zen1200030
2Alpha XOrbit1850012
3Nova 7Zen155008
4Pixel GoLumo990045
5Alpha ZOrbit220005
6Lite 2Lumo750060
  1. Show the Model and Price of the mobiles whose Brand is 'Zen'.
  2. Show the number of mobiles in each Brand.
  3. Show the mobiles whose Price is from 9000 to 16000.
  4. Increase the Price by 500 for the mobiles whose Brand is 'Zen'.
Answer
(i)
SELECT Model, Price FROM MOBILE WHERE Brand = 'Zen';
ModelPrice
Nova 512000
Nova 715500

Explanation: WHERE keeps only the rows where Brand is 'Zen': 2 of the 6 rows match (Nova 5, Nova 7).

(ii)
SELECT Brand, COUNT(*) FROM MOBILE GROUP BY Brand;
BrandCOUNT(*)
Lumo2
Orbit2
Zen2

Explanation: GROUP BY Brand makes 3 groups (Lumo, Orbit, Zen); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
SELECT * FROM MOBILE WHERE Price BETWEEN 9000 AND 16000;
MIDModelBrandPriceStock
1Nova 5Zen1200030
3Nova 7Zen155008
4Pixel GoLumo990045

Explanation: WHERE keeps only the rows where Price is from 9000 to 16000 (both included): 3 of the 6 rows match (Nova 5, Nova 7, Pixel Go).

(iv)
UPDATE MOBILE SET Price = Price + 500 WHERE Brand = 'Zen';

2 rows changed.

Explanation: SET Price = Price + 500 changes the value; WHERE limits the change to the rows where Brand is 'Zen': 2 rows changed.

D1.21Practice4 marks

Write SQL queries for the following, based on the table MOBILE.

Table: MOBILE

MIDModelBrandPriceStock
1Nova 5Zen1200030
2Alpha XOrbit1850012
3Nova 7Zen155008
4Pixel GoLumo990045
5Alpha ZOrbit220005
6Lite 2Lumo750060
  1. Show all the mobiles in descending order of Price.
  2. Show the highest and the lowest Price.
  3. Show the Model of the mobiles whose Model starts with Alpha.
  4. Delete the mobiles whose Price is less than 10000.
Answer
(i)
SELECT * FROM MOBILE ORDER BY Price DESC;
MIDModelBrandPriceStock
5Alpha ZOrbit220005
2Alpha XOrbit1850012
3Nova 7Zen155008
1Nova 5Zen1200030
4Pixel GoLumo990045
6Lite 2Lumo750060

Explanation: ORDER BY Price arranges the result in descending (largest first) order.

(ii)
SELECT MAX(Price), MIN(Price) FROM MOBILE;
MAX(Price)MIN(Price)
220007500

Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.

(iii)
SELECT Model FROM MOBILE WHERE Model LIKE 'Alpha%';
Model
Alpha X
Alpha Z

Explanation: WHERE keeps only the rows where Model matches the pattern 'Alpha%': 2 of the 6 rows match (Alpha X, Alpha Z). 'Alpha%' means the value starts with 'Alpha'.

(iv)
DELETE FROM MOBILE WHERE Price < 10000;

2 rows changed.

Explanation: WHERE picks the rows where Price is less than 10000: 2 rows are deleted; the table and the other rows remain.

D1.22Practice4 marks

Write SQL queries for the following, based on the table MOBILE.

Table: MOBILE

MIDModelBrandPriceStock
1Nova 5Zen1200030
2Alpha XOrbit1850012
3Nova 7Zen155008
4Pixel GoLumo990045
5Alpha ZOrbit220005
6Lite 2Lumo750060
  1. Show the different values of Brand.
  2. Show each Brand that has more than one mobile, with the count.
  3. Show the Model of the mobiles whose Brand is 'Zen' or 'Lumo'.
  4. Show the total Price of the mobiles whose Brand is 'Lumo'.
Answer
(i)
SELECT DISTINCT Brand FROM MOBILE;
Brand
Zen
Orbit
Lumo

Explanation: DISTINCT removes the repeated rows from the result of all the rows.

(ii)
SELECT Brand, COUNT(*) FROM MOBILE GROUP BY Brand HAVING COUNT(*) > 1;
BrandCOUNT(*)
Lumo2
Orbit2
Zen2

Explanation: GROUP BY Brand makes 3 groups (Lumo, Orbit, Zen); the aggregate function is worked out separately for each group. HAVING then keeps only the groups where COUNT(*) is more than 1. COUNT(*) counts the rows.

(iii)
SELECT Model FROM MOBILE WHERE Brand IN ('Zen', 'Lumo');
Model
Nova 5
Nova 7
Pixel Go
Lite 2

Explanation: WHERE keeps only the rows where Brand is one of ('Zen', 'Lumo'): 4 of the 6 rows match (Nova 5, Nova 7, Pixel Go, Lite 2).

(iv)
SELECT SUM(Price) FROM MOBILE WHERE Brand = 'Lumo';
SUM(Price)
17400

Explanation: WHERE keeps only the rows where Brand is 'Lumo': 2 of the 6 rows match (Pixel Go, Lite 2). SUM adds the values of the matching rows.

D1.23Practice4 marks

Write SQL queries for the following, based on the table PATIENT.

Table: PATIENT

PIDPNameWardDaysBill
1MohanGeneral34500
2RekhaICU532000
3ManojGeneral22800
4FarahPrivate418000
5MeenaICU215000
6GopalPrivate627000
  1. Show the PName and Bill of the patients whose Ward is 'ICU'.
  2. Show the number of patients in each Ward.
  3. Show the patients whose Bill is from 4000 to 20000.
  4. Increase the Bill by 1000 for the patients whose Ward is 'ICU'.
Answer
(i)
SELECT PName, Bill FROM PATIENT WHERE Ward = 'ICU';
PNameBill
Rekha32000
Meena15000

Explanation: WHERE keeps only the rows where Ward is 'ICU': 2 of the 6 rows match (Rekha, Meena).

(ii)
SELECT Ward, COUNT(*) FROM PATIENT GROUP BY Ward;
WardCOUNT(*)
General2
ICU2
Private2

Explanation: GROUP BY Ward makes 3 groups (General, ICU, Private); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
SELECT * FROM PATIENT WHERE Bill BETWEEN 4000 AND 20000;
PIDPNameWardDaysBill
1MohanGeneral34500
4FarahPrivate418000
5MeenaICU215000

Explanation: WHERE keeps only the rows where Bill is from 4000 to 20000 (both included): 3 of the 6 rows match (Mohan, Farah, Meena).

(iv)
UPDATE PATIENT SET Bill = Bill + 1000 WHERE Ward = 'ICU';

2 rows changed.

Explanation: SET Bill = Bill + 1000 changes the value; WHERE limits the change to the rows where Ward is 'ICU': 2 rows changed.

D1.24Practice4 marks

Write SQL queries for the following, based on the table PATIENT.

Table: PATIENT

PIDPNameWardDaysBill
1MohanGeneral34500
2RekhaICU532000
3ManojGeneral22800
4FarahPrivate418000
5MeenaICU215000
6GopalPrivate627000
  1. Show all the patients in descending order of Bill.
  2. Show the highest and the lowest Bill.
  3. Show the PName of the patients whose PName starts with M.
  4. Delete the patients whose Bill is less than 5000.
Answer
(i)
SELECT * FROM PATIENT ORDER BY Bill DESC;
PIDPNameWardDaysBill
2RekhaICU532000
6GopalPrivate627000
4FarahPrivate418000
5MeenaICU215000
1MohanGeneral34500
3ManojGeneral22800

Explanation: ORDER BY Bill arranges the result in descending (largest first) order.

(ii)
SELECT MAX(Bill), MIN(Bill) FROM PATIENT;
MAX(Bill)MIN(Bill)
320002800

Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.

(iii)
SELECT PName FROM PATIENT WHERE PName LIKE 'M%';
PName
Mohan
Manoj
Meena

Explanation: WHERE keeps only the rows where PName matches the pattern 'M%': 3 of the 6 rows match (Mohan, Manoj, Meena). 'M%' means the value starts with 'M'.

(iv)
DELETE FROM PATIENT WHERE Bill < 5000;

2 rows changed.

Explanation: WHERE picks the rows where Bill is less than 5000: 2 rows are deleted; the table and the other rows remain.

D1.25Practice4 marks

Write SQL queries for the following, based on the table PATIENT.

Table: PATIENT

PIDPNameWardDaysBill
1MohanGeneral34500
2RekhaICU532000
3ManojGeneral22800
4FarahPrivate418000
5MeenaICU215000
6GopalPrivate627000
  1. Show the different values of Ward.
  2. Show each Ward that has more than one patient, with the count.
  3. Show the PName of the patients whose Ward is 'ICU' or 'Private'.
  4. Show the total Bill of the patients whose Ward is 'Private'.
Answer
(i)
SELECT DISTINCT Ward FROM PATIENT;
Ward
General
ICU
Private

Explanation: DISTINCT removes the repeated rows from the result of all the rows.

(ii)
SELECT Ward, COUNT(*) FROM PATIENT GROUP BY Ward HAVING COUNT(*) > 1;
WardCOUNT(*)
General2
ICU2
Private2

Explanation: GROUP BY Ward makes 3 groups (General, ICU, Private); the aggregate function is worked out separately for each group. HAVING then keeps only the groups where COUNT(*) is more than 1. COUNT(*) counts the rows.

(iii)
SELECT PName FROM PATIENT WHERE Ward IN ('ICU', 'Private');
PName
Rekha
Farah
Meena
Gopal

Explanation: WHERE keeps only the rows where Ward is one of ('ICU', 'Private'): 4 of the 6 rows match (Rekha, Farah, Meena, Gopal).

(iv)
SELECT SUM(Bill) FROM PATIENT WHERE Ward = 'Private';
SUM(Bill)
45000

Explanation: WHERE keeps only the rows where Ward is 'Private': 2 of the 6 rows match (Farah, Gopal). SUM adds the values of the matching rows.

D1.26Practice4 marks

Write SQL queries for the following, based on the table CLUB.

Table: CLUB

MemNoMNameSportFeeAge
1ArjunCricket150016
2NishaTennis220015
3AmanCricket150017
4PoojaChess80014
5AnkitTennis220016
6RituChess80015
  1. Show the MName and Fee of the members whose Sport is 'Cricket'.
  2. Show the number of members in each Sport.
  3. Show the members whose Fee is from 1000 to 2200.
  4. Increase the Fee by 100 for the members whose Sport is 'Cricket'.
Answer
(i)
SELECT MName, Fee FROM CLUB WHERE Sport = 'Cricket';
MNameFee
Arjun1500
Aman1500

Explanation: WHERE keeps only the rows where Sport is 'Cricket': 2 of the 6 rows match (Arjun, Aman).

(ii)
SELECT Sport, COUNT(*) FROM CLUB GROUP BY Sport;
SportCOUNT(*)
Chess2
Cricket2
Tennis2

Explanation: GROUP BY Sport makes 3 groups (Chess, Cricket, Tennis); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
SELECT * FROM CLUB WHERE Fee BETWEEN 1000 AND 2200;
MemNoMNameSportFeeAge
1ArjunCricket150016
2NishaTennis220015
3AmanCricket150017
5AnkitTennis220016

Explanation: WHERE keeps only the rows where Fee is from 1000 to 2200 (both included): 4 of the 6 rows match (Arjun, Nisha, Aman, Ankit).

(iv)
UPDATE CLUB SET Fee = Fee + 100 WHERE Sport = 'Cricket';

2 rows changed.

Explanation: SET Fee = Fee + 100 changes the value; WHERE limits the change to the rows where Sport is 'Cricket': 2 rows changed.

D1.27Practice4 marks

Write SQL queries for the following, based on the table CLUB.

Table: CLUB

MemNoMNameSportFeeAge
1ArjunCricket150016
2NishaTennis220015
3AmanCricket150017
4PoojaChess80014
5AnkitTennis220016
6RituChess80015
  1. Show all the members in descending order of Fee.
  2. Show the highest and the lowest Fee.
  3. Show the MName of the members whose MName starts with A.
  4. Delete the members whose Fee is less than 1000.
Answer
(i)
SELECT * FROM CLUB ORDER BY Fee DESC;
MemNoMNameSportFeeAge
2NishaTennis220015
5AnkitTennis220016
1ArjunCricket150016
3AmanCricket150017
4PoojaChess80014
6RituChess80015

Explanation: ORDER BY Fee arranges the result in descending (largest first) order.

(ii)
SELECT MAX(Fee), MIN(Fee) FROM CLUB;
MAX(Fee)MIN(Fee)
2200800

Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.

(iii)
SELECT MName FROM CLUB WHERE MName LIKE 'A%';
MName
Arjun
Aman
Ankit

Explanation: WHERE keeps only the rows where MName matches the pattern 'A%': 3 of the 6 rows match (Arjun, Aman, Ankit). 'A%' means the value starts with 'A'.

(iv)
DELETE FROM CLUB WHERE Fee < 1000;

2 rows changed.

Explanation: WHERE picks the rows where Fee is less than 1000: 2 rows are deleted; the table and the other rows remain.

D1.28Practice4 marks

Write SQL queries for the following, based on the table CLUB.

Table: CLUB

MemNoMNameSportFeeAge
1ArjunCricket150016
2NishaTennis220015
3AmanCricket150017
4PoojaChess80014
5AnkitTennis220016
6RituChess80015
  1. Show the different values of Sport.
  2. Show each Sport that has more than one member, with the count.
  3. Show the MName of the members whose Sport is 'Cricket' or 'Chess'.
  4. Show the total Fee of the members whose Sport is 'Chess'.
Answer
(i)
SELECT DISTINCT Sport FROM CLUB;
Sport
Cricket
Tennis
Chess

Explanation: DISTINCT removes the repeated rows from the result of all the rows.

(ii)
SELECT Sport, COUNT(*) FROM CLUB GROUP BY Sport HAVING COUNT(*) > 1;
SportCOUNT(*)
Chess2
Cricket2
Tennis2

Explanation: GROUP BY Sport makes 3 groups (Chess, Cricket, Tennis); the aggregate function is worked out separately for each group. HAVING then keeps only the groups where COUNT(*) is more than 1. COUNT(*) counts the rows.

(iii)
SELECT MName FROM CLUB WHERE Sport IN ('Cricket', 'Chess');
MName
Arjun
Aman
Pooja
Ritu

Explanation: WHERE keeps only the rows where Sport is one of ('Cricket', 'Chess'): 4 of the 6 rows match (Arjun, Aman, Pooja, Ritu).

(iv)
SELECT SUM(Fee) FROM CLUB WHERE Sport = 'Chess';
SUM(Fee)
1600

Explanation: WHERE keeps only the rows where Sport is 'Chess': 2 of the 6 rows match (Pooja, Ritu). SUM adds the values of the matching rows.

D1.29Practice4 marks

Write SQL queries for the following, based on the table GARMENT.

Table: GARMENT

GCodeGNameSizePriceQty
G1KurtaM65020
G2JeansL120015
G3ShirtM80025
G4JacketXL24006
G5SareeL180010
G6SkirtM70012
  1. Show the GName and Price of the garments whose Size is 'M'.
  2. Show the number of garments in each Size.
  3. Show the garments whose Price is from 700 to 1800.
  4. Increase the Price by 50 for the garments whose Size is 'M'.
Answer
(i)
SELECT GName, Price FROM GARMENT WHERE Size = 'M';
GNamePrice
Kurta650
Shirt800
Skirt700

Explanation: WHERE keeps only the rows where Size is 'M': 3 of the 6 rows match (G1, G3, G6).

(ii)
SELECT Size, COUNT(*) FROM GARMENT GROUP BY Size;
SizeCOUNT(*)
L2
M3
XL1

Explanation: GROUP BY Size makes 3 groups (L, M, XL); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
SELECT * FROM GARMENT WHERE Price BETWEEN 700 AND 1800;
GCodeGNameSizePriceQty
G2JeansL120015
G3ShirtM80025
G5SareeL180010
G6SkirtM70012

Explanation: WHERE keeps only the rows where Price is from 700 to 1800 (both included): 4 of the 6 rows match (G2, G3, G5, G6).

(iv)
UPDATE GARMENT SET Price = Price + 50 WHERE Size = 'M';

3 rows changed.

Explanation: SET Price = Price + 50 changes the value; WHERE limits the change to the rows where Size is 'M': 3 rows changed.

D1.30Practice4 marks

Write SQL queries for the following, based on the table GARMENT.

Table: GARMENT

GCodeGNameSizePriceQty
G1KurtaM65020
G2JeansL120015
G3ShirtM80025
G4JacketXL24006
G5SareeL180010
G6SkirtM70012
  1. Show all the garments in descending order of Price.
  2. Show the highest and the lowest Price.
  3. Show the GName of the garments whose GName starts with S.
  4. Delete the garments whose Price is less than 750.
Answer
(i)
SELECT * FROM GARMENT ORDER BY Price DESC;
GCodeGNameSizePriceQty
G4JacketXL24006
G5SareeL180010
G2JeansL120015
G3ShirtM80025
G6SkirtM70012
G1KurtaM65020

Explanation: ORDER BY Price arranges the result in descending (largest first) order.

(ii)
SELECT MAX(Price), MIN(Price) FROM GARMENT;
MAX(Price)MIN(Price)
2400650

Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.

(iii)
SELECT GName FROM GARMENT WHERE GName LIKE 'S%';
GName
Shirt
Saree
Skirt

Explanation: WHERE keeps only the rows where GName matches the pattern 'S%': 3 of the 6 rows match (G3, G5, G6). 'S%' means the value starts with 'S'.

(iv)
DELETE FROM GARMENT WHERE Price < 750;

2 rows changed.

Explanation: WHERE picks the rows where Price is less than 750: 2 rows are deleted; the table and the other rows remain.

D1.31Practice4 marks

Write SQL queries for the following, based on the table GARMENT.

Table: GARMENT

GCodeGNameSizePriceQty
G1KurtaM65020
G2JeansL120015
G3ShirtM80025
G4JacketXL24006
G5SareeL180010
G6SkirtM70012
  1. Show the different values of Size.
  2. Show each Size that has more than one garment, with the count.
  3. Show the GName of the garments whose Size is 'M' or 'L'.
  4. Show the total Price of the garments whose Size is 'L'.
Answer
(i)
SELECT DISTINCT Size FROM GARMENT;
Size
M
L
XL

Explanation: DISTINCT removes the repeated rows from the result of all the rows.

(ii)
SELECT Size, COUNT(*) FROM GARMENT GROUP BY Size HAVING COUNT(*) > 1;
SizeCOUNT(*)
L2
M3

Explanation: GROUP BY Size makes 3 groups (L, M, XL); the aggregate function is worked out separately for each group. HAVING then keeps only the groups where COUNT(*) is more than 1. COUNT(*) counts the rows.

(iii)
SELECT GName FROM GARMENT WHERE Size IN ('M', 'L');
GName
Kurta
Jeans
Shirt
Saree
Skirt

Explanation: WHERE keeps only the rows where Size is one of ('M', 'L'): 5 of the 6 rows match (G1, G2, G3, G5, G6).

(iv)
SELECT SUM(Price) FROM GARMENT WHERE Size = 'L';
SUM(Price)
3000

Explanation: WHERE keeps only the rows where Size is 'L': 2 of the 6 rows match (G2, G5). SUM adds the values of the matching rows.

D1.32Practice4 marks

Write SQL queries for the following, based on the table COURSE.

Table: COURSE

CIDCNameModeFeesSeats
C1Python BasicsOnline300060
C2Data ScienceOffline1200030
C3Web DesignOnline450050
C4Cyber SafetyOnline250080
C5RoboticsOffline900025
C6AI BasicsOffline700040
  1. Show the CName and Fees of the courses whose Mode is 'Online'.
  2. Show the number of courses in each Mode.
  3. Show the courses whose Fees is from 3000 to 9000.
  4. Increase the Fees by 500 for the courses whose Mode is 'Online'.
Answer
(i)
SELECT CName, Fees FROM COURSE WHERE Mode = 'Online';
CNameFees
Python Basics3000
Web Design4500
Cyber Safety2500

Explanation: WHERE keeps only the rows where Mode is 'Online': 3 of the 6 rows match (C1, C3, C4).

(ii)
SELECT Mode, COUNT(*) FROM COURSE GROUP BY Mode;
ModeCOUNT(*)
Offline3
Online3

Explanation: GROUP BY Mode makes 2 groups (Offline, Online); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
SELECT * FROM COURSE WHERE Fees BETWEEN 3000 AND 9000;
CIDCNameModeFeesSeats
C1Python BasicsOnline300060
C3Web DesignOnline450050
C5RoboticsOffline900025
C6AI BasicsOffline700040

Explanation: WHERE keeps only the rows where Fees is from 3000 to 9000 (both included): 4 of the 6 rows match (C1, C3, C5, C6).

(iv)
UPDATE COURSE SET Fees = Fees + 500 WHERE Mode = 'Online';

3 rows changed.

Explanation: SET Fees = Fees + 500 changes the value; WHERE limits the change to the rows where Mode is 'Online': 3 rows changed.

D1.33Practice4 marks

Write SQL queries for the following, based on the table COURSE.

Table: COURSE

CIDCNameModeFeesSeats
C1Python BasicsOnline300060
C2Data ScienceOffline1200030
C3Web DesignOnline450050
C4Cyber SafetyOnline250080
C5RoboticsOffline900025
C6AI BasicsOffline700040
  1. Show all the courses in descending order of Fees.
  2. Show the highest and the lowest Fees.
  3. Show the CName of the courses whose CName ends with Basics.
  4. Delete the courses whose Fees is less than 4000.
Answer
(i)
SELECT * FROM COURSE ORDER BY Fees DESC;
CIDCNameModeFeesSeats
C2Data ScienceOffline1200030
C5RoboticsOffline900025
C6AI BasicsOffline700040
C3Web DesignOnline450050
C1Python BasicsOnline300060
C4Cyber SafetyOnline250080

Explanation: ORDER BY Fees arranges the result in descending (largest first) order.

(ii)
SELECT MAX(Fees), MIN(Fees) FROM COURSE;
MAX(Fees)MIN(Fees)
120002500

Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.

(iii)
SELECT CName FROM COURSE WHERE CName LIKE '%Basics';
CName
Python Basics
AI Basics

Explanation: WHERE keeps only the rows where CName matches the pattern '%Basics': 2 of the 6 rows match (C1, C6). '%Basics' means the value ends with 'Basics'.

(iv)
DELETE FROM COURSE WHERE Fees < 4000;

2 rows changed.

Explanation: WHERE picks the rows where Fees is less than 4000: 2 rows are deleted; the table and the other rows remain.

D1.34Practice4 marks

Write SQL queries for the following, based on the table COURSE.

Table: COURSE

CIDCNameModeFeesSeats
C1Python BasicsOnline300060
C2Data ScienceOffline1200030
C3Web DesignOnline450050
C4Cyber SafetyOnline250080
C5RoboticsOffline900025
C6AI BasicsOffline700040
  1. Show the different values of Mode.
  2. Show each Mode that has more than one course, with the count.
  3. Show the CName of the courses whose Mode is 'Online' or 'Offline'.
  4. Show the total Fees of the courses whose Mode is 'Offline'.
Answer
(i)
SELECT DISTINCT Mode FROM COURSE;
Mode
Online
Offline

Explanation: DISTINCT removes the repeated rows from the result of all the rows.

(ii)
SELECT Mode, COUNT(*) FROM COURSE GROUP BY Mode HAVING COUNT(*) > 1;
ModeCOUNT(*)
Offline3
Online3

Explanation: GROUP BY Mode makes 2 groups (Offline, Online); the aggregate function is worked out separately for each group. HAVING then keeps only the groups where COUNT(*) is more than 1. COUNT(*) counts the rows.

(iii)
SELECT CName FROM COURSE WHERE Mode IN ('Online', 'Offline');
CName
Python Basics
Data Science
Web Design
Cyber Safety
Robotics
AI Basics

Explanation: WHERE keeps only the rows where Mode is one of ('Online', 'Offline'): 6 of the 6 rows match (C1, C2, C3, C4, C5, C6).

(iv)
SELECT SUM(Fees) FROM COURSE WHERE Mode = 'Offline';
SUM(Fees)
28000

Explanation: WHERE keeps only the rows where Mode is 'Offline': 3 of the 6 rows match (C2, C5, C6). SUM adds the values of the matching rows.

D1.35Practice4 marks

Write SQL queries for the following, based on the table HOSTEL.

Table: HOSTEL

RoomNoSNameBlockRentSem
101KiranA40001
102DeepaB45002
103KavyaA40001
104LataC52003
105KomalB45002
106DivyaC52001
  1. Show the SName and Rent of the students whose Block is 'A'.
  2. Show the number of students in each Block.
  3. Show the students whose Rent is from 4200 to 5200.
  4. Increase the Rent by 200 for the students whose Block is 'A'.
Answer
(i)
SELECT SName, Rent FROM HOSTEL WHERE Block = 'A';
SNameRent
Kiran4000
Kavya4000

Explanation: WHERE keeps only the rows where Block is 'A': 2 of the 6 rows match (Kiran, Kavya).

(ii)
SELECT Block, COUNT(*) FROM HOSTEL GROUP BY Block;
BlockCOUNT(*)
A2
B2
C2

Explanation: GROUP BY Block makes 3 groups (A, B, C); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
SELECT * FROM HOSTEL WHERE Rent BETWEEN 4200 AND 5200;
RoomNoSNameBlockRentSem
102DeepaB45002
104LataC52003
105KomalB45002
106DivyaC52001

Explanation: WHERE keeps only the rows where Rent is from 4200 to 5200 (both included): 4 of the 6 rows match (Deepa, Lata, Komal, Divya).

(iv)
UPDATE HOSTEL SET Rent = Rent + 200 WHERE Block = 'A';

2 rows changed.

Explanation: SET Rent = Rent + 200 changes the value; WHERE limits the change to the rows where Block is 'A': 2 rows changed.

D1.36Practice4 marks

Write SQL queries for the following, based on the table HOSTEL.

Table: HOSTEL

RoomNoSNameBlockRentSem
101KiranA40001
102DeepaB45002
103KavyaA40001
104LataC52003
105KomalB45002
106DivyaC52001
  1. Show all the students in descending order of Rent.
  2. Show the highest and the lowest Rent.
  3. Show the SName of the students whose SName starts with K.
  4. Delete the students whose Rent is less than 4400.
Answer
(i)
SELECT * FROM HOSTEL ORDER BY Rent DESC;
RoomNoSNameBlockRentSem
104LataC52003
106DivyaC52001
102DeepaB45002
105KomalB45002
101KiranA40001
103KavyaA40001

Explanation: ORDER BY Rent arranges the result in descending (largest first) order.

(ii)
SELECT MAX(Rent), MIN(Rent) FROM HOSTEL;
MAX(Rent)MIN(Rent)
52004000

Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.

(iii)
SELECT SName FROM HOSTEL WHERE SName LIKE 'K%';
SName
Kiran
Kavya
Komal

Explanation: WHERE keeps only the rows where SName matches the pattern 'K%': 3 of the 6 rows match (Kiran, Kavya, Komal). 'K%' means the value starts with 'K'.

(iv)
DELETE FROM HOSTEL WHERE Rent < 4400;

2 rows changed.

Explanation: WHERE picks the rows where Rent is less than 4400: 2 rows are deleted; the table and the other rows remain.

D1.37Practice4 marks

Write SQL queries for the following, based on the table HOSTEL.

Table: HOSTEL

RoomNoSNameBlockRentSem
101KiranA40001
102DeepaB45002
103KavyaA40001
104LataC52003
105KomalB45002
106DivyaC52001
  1. Show the different values of Block.
  2. Show each Block that has more than one student, with the count.
  3. Show the SName of the students whose Block is 'A' or 'C'.
  4. Show the total Rent of the students whose Block is 'C'.
Answer
(i)
SELECT DISTINCT Block FROM HOSTEL;
Block
A
B
C

Explanation: DISTINCT removes the repeated rows from the result of all the rows.

(ii)
SELECT Block, COUNT(*) FROM HOSTEL GROUP BY Block HAVING COUNT(*) > 1;
BlockCOUNT(*)
A2
B2
C2

Explanation: GROUP BY Block makes 3 groups (A, B, C); the aggregate function is worked out separately for each group. HAVING then keeps only the groups where COUNT(*) is more than 1. COUNT(*) counts the rows.

(iii)
SELECT SName FROM HOSTEL WHERE Block IN ('A', 'C');
SName
Kiran
Kavya
Lata
Divya

Explanation: WHERE keeps only the rows where Block is one of ('A', 'C'): 4 of the 6 rows match (Kiran, Kavya, Lata, Divya).

(iv)
SELECT SUM(Rent) FROM HOSTEL WHERE Block = 'C';
SUM(Rent)
10400

Explanation: WHERE keeps only the rows where Block is 'C': 2 of the 6 rows match (Lata, Divya). SUM adds the values of the matching rows.

D1.38Practice4 marks

Write SQL queries for the following, based on the table BUS.

Table: BUS

BusNoRouteDepotSeatsFare
B1Airport LinkNorth4060
B2City CircleSouth5225
B3Metro FeederNorth3015
B4Ring RoadEast5235
B5Hill ViewSouth3645
B6Lake LineEast4030
  1. Show the Route and Fare of the buses whose Depot is 'North'.
  2. Show the number of buses in each Depot.
  3. Show the buses whose Fare is from 25 to 45.
  4. Increase the Fare by 5 for the buses whose Depot is 'North'.
Answer
(i)
SELECT Route, Fare FROM BUS WHERE Depot = 'North';
RouteFare
Airport Link60
Metro Feeder15

Explanation: WHERE keeps only the rows where Depot is 'North': 2 of the 6 rows match (B1, B3).

(ii)
SELECT Depot, COUNT(*) FROM BUS GROUP BY Depot;
DepotCOUNT(*)
East2
North2
South2

Explanation: GROUP BY Depot makes 3 groups (East, North, South); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iii)
SELECT * FROM BUS WHERE Fare BETWEEN 25 AND 45;
BusNoRouteDepotSeatsFare
B2City CircleSouth5225
B4Ring RoadEast5235
B5Hill ViewSouth3645
B6Lake LineEast4030

Explanation: WHERE keeps only the rows where Fare is from 25 to 45 (both included): 4 of the 6 rows match (B2, B4, B5, B6).

(iv)
UPDATE BUS SET Fare = Fare + 5 WHERE Depot = 'North';

2 rows changed.

Explanation: SET Fare = Fare + 5 changes the value; WHERE limits the change to the rows where Depot is 'North': 2 rows changed.

D1.39Practice4 marks

Write SQL queries for the following, based on the table BUS.

Table: BUS

BusNoRouteDepotSeatsFare
B1Airport LinkNorth4060
B2City CircleSouth5225
B3Metro FeederNorth3015
B4Ring RoadEast5235
B5Hill ViewSouth3645
B6Lake LineEast4030
  1. Show all the buses in descending order of Fare.
  2. Show the highest and the lowest Fare.
  3. Show the Route of the buses whose Route contains Li.
  4. Delete the buses whose Fare is less than 30.
Answer
(i)
SELECT * FROM BUS ORDER BY Fare DESC;
BusNoRouteDepotSeatsFare
B1Airport LinkNorth4060
B5Hill ViewSouth3645
B4Ring RoadEast5235
B6Lake LineEast4030
B2City CircleSouth5225
B3Metro FeederNorth3015

Explanation: ORDER BY Fare arranges the result in descending (largest first) order.

(ii)
SELECT MAX(Fare), MIN(Fare) FROM BUS;
MAX(Fare)MIN(Fare)
6015

Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.

(iii)
SELECT Route FROM BUS WHERE Route LIKE '%Li%';
Route
Airport Link
Lake Line

Explanation: WHERE keeps only the rows where Route matches the pattern '%Li%': 2 of the 6 rows match (B1, B6). '%Li%' means the value contains 'Li'.

(iv)
DELETE FROM BUS WHERE Fare < 30;

2 rows changed.

Explanation: WHERE picks the rows where Fare is less than 30: 2 rows are deleted; the table and the other rows remain.

D1.40Practice4 marks

Write SQL queries for the following, based on the table BUS.

Table: BUS

BusNoRouteDepotSeatsFare
B1Airport LinkNorth4060
B2City CircleSouth5225
B3Metro FeederNorth3015
B4Ring RoadEast5235
B5Hill ViewSouth3645
B6Lake LineEast4030
  1. Show the different values of Depot.
  2. Show each Depot that has more than one bus, with the count.
  3. Show the Route of the buses whose Depot is 'North' or 'East'.
  4. Show the total Fare of the buses whose Depot is 'East'.
Answer
(i)
SELECT DISTINCT Depot FROM BUS;
Depot
North
South
East

Explanation: DISTINCT removes the repeated rows from the result of all the rows.

(ii)
SELECT Depot, COUNT(*) FROM BUS GROUP BY Depot HAVING COUNT(*) > 1;
DepotCOUNT(*)
East2
North2
South2

Explanation: GROUP BY Depot makes 3 groups (East, North, South); the aggregate function is worked out separately for each group. HAVING then keeps only the groups where COUNT(*) is more than 1. COUNT(*) counts the rows.

(iii)
SELECT Route FROM BUS WHERE Depot IN ('North', 'East');
Route
Airport Link
Metro Feeder
Ring Road
Lake Line

Explanation: WHERE keeps only the rows where Depot is one of ('North', 'East'): 4 of the 6 rows match (B1, B3, B4, B6).

(iv)
SELECT SUM(Fare) FROM BUS WHERE Depot = 'East';
SUM(Fare)
65

Explanation: WHERE keeps only the rows where Depot is 'East': 2 of the 6 rows match (B4, B6). SUM adds the values of the matching rows.

D2CSV file functions4 marks · 40 questions
D2.1SQP 2026-274 marks

Rentals.csv stores Vehicle_ID, Vehicle_Type, Hours_Rented, Rate_Per_Hour. Write AddRental() to input one record and append it to the file, and CalculateTotalRent() to return the total rent (Hours_Rented x Rate_Per_Hour of all records).

Answer
import csv
def AddRental():
    f = open("Rentals.csv", "a", newline="")
    w = csv.writer(f)
    vid = input("Vehicle ID: ")
    vtype = input("Vehicle type: ")
    hrs = int(input("Hours rented: "))
    rate = int(input("Rate per hour: "))
    w.writerow([vid, vtype, hrs, rate])
    f.close()

def CalculateTotalRent():
    f = open("Rentals.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[2]) * int(row[3])
    f.close()
    return total
D2.2CBSE 20264 marks

States.csv has a header row and one row for every state, including its population. Write a program that copies the records with population above 1,00,00,000 into More.csv.

Answer

Use the column position of population given in the question paper; index 2 is taken here.

import csv
fin = open("States.csv", "r")
fout = open("More.csv", "a", newline="")
r = csv.reader(fin)
w = csv.writer(fout)
next(r)                          # skip the header row
for row in r:
    if int(row[2]) > 10000000:
        w.writerow(row)
fin.close()
fout.close()
D2.3CBSE 20254 marks

P_record.csv stores patient name, disease, days admitted and amount. Write read_data() to display the records of the patients whose disease is "Cancer", and count_rec() to return the number of records.

Answer
import csv
def read_data():
    f = open("P_record.csv", "r")
    for row in csv.reader(f):
        if row[1] == "Cancer":
            print(row)
    f.close()

def count_rec():
    f = open("P_record.csv", "r")
    c = 0
    for row in csv.reader(f):
        c += 1
    f.close()
    return c
D2.4Practice4 marks

Student.csv stores RNo, Name, Marks. Write Add() to input one record and append it, and Topper() to display the records with marks above 90.

Answer
import csv
def Add():
    f = open("Student.csv", "a", newline="")
    w = csv.writer(f)
    rno = int(input("Roll no: "))
    name = input("Name: ")
    marks = int(input("Marks: "))
    w.writerow([rno, name, marks])
    f.close()

def Topper():
    f = open("Student.csv", "r")
    for row in csv.reader(f):
        if int(row[2]) > 90:
            print(row)
    f.close()
D2.5Practice4 marks

Item.csv stores ICode, IName, Price, Qty. Write LowStock() to display the items with Qty below 10 and to print how many such items there are.

Answer
import csv
def LowStock():
    f = open("Item.csv", "r")
    c = 0
    for row in csv.reader(f):
        if int(row[3]) < 10:
            print(row)
            c += 1
    print("Items low in stock:", c)
    f.close()
D2.6Practice4 marks

Emp.csv has the header ENo, EName, Dept, Salary. Write ShowHR() to display the names of the employees of the 'HR' department, leaving out the header row.

Answer
import csv
def ShowHR():
    f = open("Emp.csv", "r")
    r = csv.reader(f)
    next(r)                      # skip the header row
    for row in r:
        if row[2] == "HR":
            print(row[1])
    f.close()
D2.7Practice4 marks

Books.csv stores BNo, Title, Price. Write Search() to input a book number and display its record, or "Not found".

Answer
import csv
def Search():
    bno = input("Book number: ")
    f = open("Books.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == bno:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D2.8Practice4 marks

Score.csv stores Player, Runs. Write Highest() to display the name and runs of the highest scorer.

Answer
import csv
def Highest():
    f = open("Score.csv", "r")
    top = 0
    name = ""
    for row in csv.reader(f):
        if int(row[1]) > top:
            top = int(row[1])
            name = row[0]
    print(name, top)
    f.close()
D2.9Practice4 marks

Result.csv stores RNo, Name, Marks. Write CopyFail() to copy the records with marks below 33 into Fail.csv.

Answer
import csv
def CopyFail():
    fin = open("Result.csv", "r")
    fout = open("Fail.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[2]) < 33:
            w.writerow(row)
    fin.close()
    fout.close()
D2.10Practice4 marks

Weather.csv stores City, Temperature. Write AvgTemp() to return the average temperature of all the cities.

Answer
import csv
def AvgTemp():
    f = open("Weather.csv", "r")
    total = 0
    n = 0
    for row in csv.reader(f):
        total += float(row[1])
        n += 1
    f.close()
    return total / n
D2.11Practice4 marks

Library.csv stores BookNo, Title, Subject, Price. Write AddBook() to input one record and append it to the file, and ShowBook() to display the records whose Price is more than 300.

Answer
import csv
def AddBook():
    f = open("Library.csv", "a", newline="")
    w = csv.writer(f)
    bookno = input("BookNo: ")
    title = input("Title: ")
    subject = input("Subject: ")
    price = int(input("Price: "))
    w.writerow([bookno, title, subject, price])
    f.close()

def ShowBook():
    f = open("Library.csv", "r")
    for row in csv.reader(f):
        if int(row[3]) > 300:
            print(row)
    f.close()
D2.12Practice4 marks

Library.csv stores BookNo, Title, Subject, Price. Write CountBook() to return the number of records whose Subject is "Science", and TotalPrice() to return the total of Price of all the records.

Answer
import csv
def CountBook():
    f = open("Library.csv", "r")
    c = 0
    for row in csv.reader(f):
        if row[2] == "Science":
            c += 1
    f.close()
    return c

def TotalPrice():
    f = open("Library.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[3])
    f.close()
    return total
D2.13Practice4 marks

Library.csv stores BookNo, Title, Subject, Price. Write CopyBook() to copy the records whose Price is more than 300 into Costly.csv, and SearchBook() to input a BookNo and display that record, or "Not found".

Answer
import csv
def CopyBook():
    fin = open("Library.csv", "r")
    fout = open("Costly.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[3]) > 300:
            w.writerow(row)
    fin.close()
    fout.close()

def SearchBook():
    key = input("Enter BookNo: ")
    f = open("Library.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == key:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D2.14Practice4 marks

Hostel.csv stores RoomNo, Student, Block, Rent. Write AddRoom() to input one record and append it to the file, and ShowRoom() to display the records whose Rent is more than 4100.

Answer
import csv
def AddRoom():
    f = open("Hostel.csv", "a", newline="")
    w = csv.writer(f)
    roomno = input("RoomNo: ")
    student = input("Student: ")
    block = input("Block: ")
    rent = int(input("Rent: "))
    w.writerow([roomno, student, block, rent])
    f.close()

def ShowRoom():
    f = open("Hostel.csv", "r")
    for row in csv.reader(f):
        if int(row[3]) > 4100:
            print(row)
    f.close()
D2.15Practice4 marks

Hostel.csv stores RoomNo, Student, Block, Rent. Write CountRoom() to return the number of records whose Block is "A", and TotalRent() to return the total of Rent of all the records.

Answer
import csv
def CountRoom():
    f = open("Hostel.csv", "r")
    c = 0
    for row in csv.reader(f):
        if row[2] == "A":
            c += 1
    f.close()
    return c

def TotalRent():
    f = open("Hostel.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[3])
    f.close()
    return total
D2.16Practice4 marks

Hostel.csv stores RoomNo, Student, Block, Rent. Write CopyRoom() to copy the records whose Rent is more than 4100 into HighRent.csv, and SearchRoom() to input a RoomNo and display that record, or "Not found".

Answer
import csv
def CopyRoom():
    fin = open("Hostel.csv", "r")
    fout = open("HighRent.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[3]) > 4100:
            w.writerow(row)
    fin.close()
    fout.close()

def SearchRoom():
    key = input("Enter RoomNo: ")
    f = open("Hostel.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == key:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D2.17Practice4 marks

Canteen.csv stores ItemNo, Item, Category, Price. Write AddItem() to input one record and append it to the file, and ShowItem() to display the records whose Price is more than 20.

Answer
import csv
def AddItem():
    f = open("Canteen.csv", "a", newline="")
    w = csv.writer(f)
    itemno = input("ItemNo: ")
    item = input("Item: ")
    category = input("Category: ")
    price = int(input("Price: "))
    w.writerow([itemno, item, category, price])
    f.close()

def ShowItem():
    f = open("Canteen.csv", "r")
    for row in csv.reader(f):
        if int(row[3]) > 20:
            print(row)
    f.close()
D2.18Practice4 marks

Canteen.csv stores ItemNo, Item, Category, Price. Write CountItem() to return the number of records whose Category is "Snack", and TotalPrice() to return the total of Price of all the records.

Answer
import csv
def CountItem():
    f = open("Canteen.csv", "r")
    c = 0
    for row in csv.reader(f):
        if row[2] == "Snack":
            c += 1
    f.close()
    return c

def TotalPrice():
    f = open("Canteen.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[3])
    f.close()
    return total
D2.19Practice4 marks

Canteen.csv stores ItemNo, Item, Category, Price. Write CopyItem() to copy the records whose Price is more than 20 into Special.csv, and SearchItem() to input a ItemNo and display that record, or "Not found".

Answer
import csv
def CopyItem():
    fin = open("Canteen.csv", "r")
    fout = open("Special.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[3]) > 20:
            w.writerow(row)
    fin.close()
    fout.close()

def SearchItem():
    key = input("Enter ItemNo: ")
    f = open("Canteen.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == key:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D2.20Practice4 marks

Sports.csv stores PNo, Player, Game, Points. Write AddPlayer() to input one record and append it to the file, and ShowPlayer() to display the records whose Points is more than 70.

Answer
import csv
def AddPlayer():
    f = open("Sports.csv", "a", newline="")
    w = csv.writer(f)
    pno = input("PNo: ")
    player = input("Player: ")
    game = input("Game: ")
    points = int(input("Points: "))
    w.writerow([pno, player, game, points])
    f.close()

def ShowPlayer():
    f = open("Sports.csv", "r")
    for row in csv.reader(f):
        if int(row[3]) > 70:
            print(row)
    f.close()
D2.21Practice4 marks

Sports.csv stores PNo, Player, Game, Points. Write CountPlayer() to return the number of records whose Game is "Hockey", and TotalPoints() to return the total of Points of all the records.

Answer
import csv
def CountPlayer():
    f = open("Sports.csv", "r")
    c = 0
    for row in csv.reader(f):
        if row[2] == "Hockey":
            c += 1
    f.close()
    return c

def TotalPoints():
    f = open("Sports.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[3])
    f.close()
    return total
D2.22Practice4 marks

Sports.csv stores PNo, Player, Game, Points. Write CopyPlayer() to copy the records whose Points is more than 70 into Best.csv, and SearchPlayer() to input a PNo and display that record, or "Not found".

Answer
import csv
def CopyPlayer():
    fin = open("Sports.csv", "r")
    fout = open("Best.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[3]) > 70:
            w.writerow(row)
    fin.close()
    fout.close()

def SearchPlayer():
    key = input("Enter PNo: ")
    f = open("Sports.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == key:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D2.23Practice4 marks

Tour.csv stores TNo, Place, State, Cost. Write AddTour() to input one record and append it to the file, and ShowTour() to display the records whose Cost is more than 7000.

Answer
import csv
def AddTour():
    f = open("Tour.csv", "a", newline="")
    w = csv.writer(f)
    tno = input("TNo: ")
    place = input("Place: ")
    state = input("State: ")
    cost = int(input("Cost: "))
    w.writerow([tno, place, state, cost])
    f.close()

def ShowTour():
    f = open("Tour.csv", "r")
    for row in csv.reader(f):
        if int(row[3]) > 7000:
            print(row)
    f.close()
D2.24Practice4 marks

Tour.csv stores TNo, Place, State, Cost. Write CountTour() to return the number of records whose State is "Himachal", and TotalCost() to return the total of Cost of all the records.

Answer
import csv
def CountTour():
    f = open("Tour.csv", "r")
    c = 0
    for row in csv.reader(f):
        if row[2] == "Himachal":
            c += 1
    f.close()
    return c

def TotalCost():
    f = open("Tour.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[3])
    f.close()
    return total
D2.25Practice4 marks

Tour.csv stores TNo, Place, State, Cost. Write CopyTour() to copy the records whose Cost is more than 7000 into Premium.csv, and SearchTour() to input a TNo and display that record, or "Not found".

Answer
import csv
def CopyTour():
    fin = open("Tour.csv", "r")
    fout = open("Premium.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[3]) > 7000:
            w.writerow(row)
    fin.close()
    fout.close()

def SearchTour():
    key = input("Enter TNo: ")
    f = open("Tour.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == key:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D2.26Practice4 marks

Staff.csv stores ENo, EName, Dept, Pay. Write AddStaff() to input one record and append it to the file, and ShowStaff() to display the records whose Pay is more than 50000.

Answer
import csv
def AddStaff():
    f = open("Staff.csv", "a", newline="")
    w = csv.writer(f)
    eno = input("ENo: ")
    ename = input("EName: ")
    dept = input("Dept: ")
    pay = int(input("Pay: "))
    w.writerow([eno, ename, dept, pay])
    f.close()

def ShowStaff():
    f = open("Staff.csv", "r")
    for row in csv.reader(f):
        if int(row[3]) > 50000:
            print(row)
    f.close()
D2.27Practice4 marks

Staff.csv stores ENo, EName, Dept, Pay. Write CountStaff() to return the number of records whose Dept is "IT", and TotalPay() to return the total of Pay of all the records.

Answer
import csv
def CountStaff():
    f = open("Staff.csv", "r")
    c = 0
    for row in csv.reader(f):
        if row[2] == "IT":
            c += 1
    f.close()
    return c

def TotalPay():
    f = open("Staff.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[3])
    f.close()
    return total
D2.28Practice4 marks

Staff.csv stores ENo, EName, Dept, Pay. Write CopyStaff() to copy the records whose Pay is more than 50000 into Senior.csv, and SearchStaff() to input a ENo and display that record, or "Not found".

Answer
import csv
def CopyStaff():
    fin = open("Staff.csv", "r")
    fout = open("Senior.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[3]) > 50000:
            w.writerow(row)
    fin.close()
    fout.close()

def SearchStaff():
    key = input("Enter ENo: ")
    f = open("Staff.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == key:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D2.29Practice4 marks

Garden.csv stores PlantNo, Plant, Kind, Height. Write AddPlant() to input one record and append it to the file, and ShowPlant() to display the records whose Height is more than 100.

Answer
import csv
def AddPlant():
    f = open("Garden.csv", "a", newline="")
    w = csv.writer(f)
    plantno = input("PlantNo: ")
    plant = input("Plant: ")
    kind = input("Kind: ")
    height = int(input("Height: "))
    w.writerow([plantno, plant, kind, height])
    f.close()

def ShowPlant():
    f = open("Garden.csv", "r")
    for row in csv.reader(f):
        if int(row[3]) > 100:
            print(row)
    f.close()
D2.30Practice4 marks

Garden.csv stores PlantNo, Plant, Kind, Height. Write CountPlant() to return the number of records whose Kind is "Tree", and TotalHeight() to return the total of Height of all the records.

Answer
import csv
def CountPlant():
    f = open("Garden.csv", "r")
    c = 0
    for row in csv.reader(f):
        if row[2] == "Tree":
            c += 1
    f.close()
    return c

def TotalHeight():
    f = open("Garden.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[3])
    f.close()
    return total
D2.31Practice4 marks

Garden.csv stores PlantNo, Plant, Kind, Height. Write CopyPlant() to copy the records whose Height is more than 100 into Tall.csv, and SearchPlant() to input a PlantNo and display that record, or "Not found".

Answer
import csv
def CopyPlant():
    fin = open("Garden.csv", "r")
    fout = open("Tall.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[3]) > 100:
            w.writerow(row)
    fin.close()
    fout.close()

def SearchPlant():
    key = input("Enter PlantNo: ")
    f = open("Garden.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == key:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D2.32Practice4 marks

Phone.csv stores MID, Model, Brand, Price. Write AddPhone() to input one record and append it to the file, and ShowPhone() to display the records whose Price is more than 10000.

Answer
import csv
def AddPhone():
    f = open("Phone.csv", "a", newline="")
    w = csv.writer(f)
    mid = input("MID: ")
    model = input("Model: ")
    brand = input("Brand: ")
    price = int(input("Price: "))
    w.writerow([mid, model, brand, price])
    f.close()

def ShowPhone():
    f = open("Phone.csv", "r")
    for row in csv.reader(f):
        if int(row[3]) > 10000:
            print(row)
    f.close()
D2.33Practice4 marks

Phone.csv stores MID, Model, Brand, Price. Write CountPhone() to return the number of records whose Brand is "Zen", and TotalPrice() to return the total of Price of all the records.

Answer
import csv
def CountPhone():
    f = open("Phone.csv", "r")
    c = 0
    for row in csv.reader(f):
        if row[2] == "Zen":
            c += 1
    f.close()
    return c

def TotalPrice():
    f = open("Phone.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[3])
    f.close()
    return total
D2.34Practice4 marks

Phone.csv stores MID, Model, Brand, Price. Write CopyPhone() to copy the records whose Price is more than 10000 into Flagship.csv, and SearchPhone() to input a MID and display that record, or "Not found".

Answer
import csv
def CopyPhone():
    fin = open("Phone.csv", "r")
    fout = open("Flagship.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[3]) > 10000:
            w.writerow(row)
    fin.close()
    fout.close()

def SearchPhone():
    key = input("Enter MID: ")
    f = open("Phone.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == key:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D2.35Practice4 marks

Exam.csv stores RNo, Name, Stream, Marks. Write AddResult() to input one record and append it to the file, and ShowResult() to display the records whose Marks is more than 80.

Answer
import csv
def AddResult():
    f = open("Exam.csv", "a", newline="")
    w = csv.writer(f)
    rno = input("RNo: ")
    name = input("Name: ")
    stream = input("Stream: ")
    marks = int(input("Marks: "))
    w.writerow([rno, name, stream, marks])
    f.close()

def ShowResult():
    f = open("Exam.csv", "r")
    for row in csv.reader(f):
        if int(row[3]) > 80:
            print(row)
    f.close()
D2.36Practice4 marks

Exam.csv stores RNo, Name, Stream, Marks. Write CountResult() to return the number of records whose Stream is "Science", and TotalMarks() to return the total of Marks of all the records.

Answer
import csv
def CountResult():
    f = open("Exam.csv", "r")
    c = 0
    for row in csv.reader(f):
        if row[2] == "Science":
            c += 1
    f.close()
    return c

def TotalMarks():
    f = open("Exam.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[3])
    f.close()
    return total
D2.37Practice4 marks

Exam.csv stores RNo, Name, Stream, Marks. Write CopyResult() to copy the records whose Marks is more than 80 into Merit.csv, and SearchResult() to input a RNo and display that record, or "Not found".

Answer
import csv
def CopyResult():
    fin = open("Exam.csv", "r")
    fout = open("Merit.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[3]) > 80:
            w.writerow(row)
    fin.close()
    fout.close()

def SearchResult():
    key = input("Enter RNo: ")
    f = open("Exam.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == key:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D2.38Practice4 marks

Bus.csv stores BusNo, Route, Depot, Fare. Write AddBus() to input one record and append it to the file, and ShowBus() to display the records whose Fare is more than 30.

Answer
import csv
def AddBus():
    f = open("Bus.csv", "a", newline="")
    w = csv.writer(f)
    busno = input("BusNo: ")
    route = input("Route: ")
    depot = input("Depot: ")
    fare = int(input("Fare: "))
    w.writerow([busno, route, depot, fare])
    f.close()

def ShowBus():
    f = open("Bus.csv", "r")
    for row in csv.reader(f):
        if int(row[3]) > 30:
            print(row)
    f.close()
D2.39Practice4 marks

Bus.csv stores BusNo, Route, Depot, Fare. Write CountBus() to return the number of records whose Depot is "North", and TotalFare() to return the total of Fare of all the records.

Answer
import csv
def CountBus():
    f = open("Bus.csv", "r")
    c = 0
    for row in csv.reader(f):
        if row[2] == "North":
            c += 1
    f.close()
    return c

def TotalFare():
    f = open("Bus.csv", "r")
    total = 0
    for row in csv.reader(f):
        total += int(row[3])
    f.close()
    return total
D2.40Practice4 marks

Bus.csv stores BusNo, Route, Depot, Fare. Write CopyBus() to copy the records whose Fare is more than 30 into Express.csv, and SearchBus() to input a BusNo and display that record, or "Not found".

Answer
import csv
def CopyBus():
    fin = open("Bus.csv", "r")
    fout = open("Express.csv", "w", newline="")
    w = csv.writer(fout)
    for row in csv.reader(fin):
        if int(row[3]) > 30:
            w.writerow(row)
    fin.close()
    fout.close()

def SearchBus():
    key = input("Enter BusNo: ")
    f = open("Bus.csv", "r")
    found = False
    for row in csv.reader(f):
        if row[0] == key:
            print(row)
            found = True
    if not found:
        print("Not found")
    f.close()
D3SQL queries on two tables4 marks · 40 questions
D3.1SQP 2026-274 marks

Tables Chess_Event (Event_ID, Event_Name, Event_Date, Venue, Max_Participants) and Registrations (Reg_ID, Student_Name, Class, Event_ID, Registration_Date). Write queries to:

  1. Change the venue of 'Inter-School Chess Championship' to 'Multi-Purpose Hall'
  2. Show the chess events held after 2025-01-01
  3. Show the registrations for the events held in 'Auditorium Hall', 'Activity Room 3' or 'Library Conference Area'
  4. Show (a) student names with their event names, OR (b) the Cartesian product of the two tables.

Table: Chess_Event

Event_IDEvent_NameEvent_DateVenueMax_Participants
Columns only. The rows are given in the question paper.

Table: Registrations

Reg_IDStudent_NameClassEvent_IDRegistration_Date
Columns only. The rows are given in the question paper.
Answer
UPDATE Chess_Event SET Venue = 'Multi-Purpose Hall'
  WHERE Event_Name = 'Inter-School Chess Championship';
SELECT * FROM Chess_Event WHERE Event_Date > '2025-01-01';
SELECT R.* FROM Registrations R, Chess_Event C
  WHERE R.Event_ID = C.Event_ID
  AND Venue IN ('Auditorium Hall', 'Activity Room 3', 'Library Conference Area');
SELECT Student_Name, Event_Name FROM Registrations R, Chess_Event C
  WHERE R.Event_ID = C.Event_ID;
SELECT * FROM Chess_Event, Registrations;
D3.2CBSE 20264 marks

Tables CUSTOMERS (C_ID, C_Name ...) and LOANS (C_ID, L_Amt, RoI, L_Date, Terms ...). Write queries to:

  1. Count the loans with RoI above 7.0
  2. Show the names of customers whose loan amount is above 10,00,000
  3. Show C_ID, name and terms of the loans taken after 31 December 2024
  4. (a) list the loans in descending order of RoI, OR (b) show the average terms for each customer.

Table: CUSTOMERS

C_IDC_Name
Columns only. The rows are given in the question paper.

Table: LOANS

C_IDL_AmtRoIL_DateTerms
Columns only. The rows are given in the question paper.
Answer
SELECT COUNT(*) FROM LOANS WHERE RoI > 7.0;
SELECT C_Name FROM CUSTOMERS C, LOANS L
  WHERE C.C_ID = L.C_ID AND L_Amt > 1000000;
SELECT L.C_ID, C_Name, Terms FROM CUSTOMERS C, LOANS L
  WHERE C.C_ID = L.C_ID AND L_Date > '2024-12-31';
SELECT * FROM LOANS ORDER BY RoI DESC;
SELECT C_ID, AVG(Terms) FROM LOANS GROUP BY C_ID;
D3.3CBSE 20254 marks

Tables Artists (A_Code, Name ...) and Articles (A_Code, Article, DOC, Price ...). Write queries to:

  1. List the articles in descending order of price
  2. Show the articles created in the year 2020
  3. Show the structure of the table Artists
  4. Show the names of the artists who made a 'Painting'.

Table: Artists

A_CodeName
Columns only. The rows are given in the question paper.

Table: Articles

A_CodeArticleDOCPrice
Columns only. The rows are given in the question paper.
Answer
SELECT * FROM Articles ORDER BY Price DESC;
SELECT * FROM Articles WHERE YEAR(DOC) = 2020;
DESC Artists;
SELECT Name FROM Artists, Articles
  WHERE Artists.A_Code = Articles.A_Code AND Article = 'Painting';
D3.4Practice4 marks

Tables STUDENT (RNo, Name, Class) and FEE (RNo, Amount, PayDate). Write queries to:

  1. Show each student's name with the amount paid
  2. Show the names of students who paid more than 5000
  3. Show the total fee collected from each class
  4. Show all columns using a natural join.

Table: STUDENT

RNoNameClass
Columns only. The rows are given in the question paper.

Table: FEE

RNoAmountPayDate
Columns only. The rows are given in the question paper.
Answer
SELECT Name, Amount FROM STUDENT S, FEE F WHERE S.RNo = F.RNo;
SELECT Name FROM STUDENT S, FEE F WHERE S.RNo = F.RNo AND Amount > 5000;
SELECT Class, SUM(Amount) FROM STUDENT S, FEE F
  WHERE S.RNo = F.RNo GROUP BY Class;
SELECT * FROM STUDENT NATURAL JOIN FEE;
D3.5Practice4 marks

Tables EMPLOYEE (ENo, EName, DNo, Salary) and DEPARTMENT (DNo, DName, Location). Write queries to:

  1. Show employee names with their department names
  2. Show the employees working at the 'Mumbai' location
  3. Show each department name with its number of employees
  4. Change the location of the 'Sales' department to 'Pune'.

Table: EMPLOYEE

ENoENameDNoSalary
Columns only. The rows are given in the question paper.

Table: DEPARTMENT

DNoDNameLocation
Columns only. The rows are given in the question paper.
Answer
SELECT EName, DName FROM EMPLOYEE E, DEPARTMENT D WHERE E.DNo = D.DNo;
SELECT EName FROM EMPLOYEE E, DEPARTMENT D
  WHERE E.DNo = D.DNo AND Location = 'Mumbai';
SELECT DName, COUNT(*) FROM EMPLOYEE E, DEPARTMENT D
  WHERE E.DNo = D.DNo GROUP BY DName;
UPDATE DEPARTMENT SET Location = 'Pune' WHERE DName = 'Sales';
D3.6Practice4 marks

Tables PRODUCT (PID, PName, SID, Price) and SUPPLIER (SID, SName, City). Write queries to:

  1. Show product names with supplier names
  2. Show the products costing more than 500 that come from 'Delhi' suppliers
  3. Show each supplier's name with the highest price among its products
  4. Show the Cartesian product of the two tables.

Table: PRODUCT

PIDPNameSIDPrice
Columns only. The rows are given in the question paper.

Table: SUPPLIER

SIDSNameCity
Columns only. The rows are given in the question paper.
Answer
SELECT PName, SName FROM PRODUCT P, SUPPLIER S WHERE P.SID = S.SID;
SELECT PName FROM PRODUCT P, SUPPLIER S
  WHERE P.SID = S.SID AND City = 'Delhi' AND Price > 500;
SELECT SName, MAX(Price) FROM PRODUCT P, SUPPLIER S
  WHERE P.SID = S.SID GROUP BY SName;
SELECT * FROM PRODUCT, SUPPLIER;
D3.7Practice4 marks

Tables DOCTOR (DID, DName, Dept) and PATIENT (PID, PName, DID, AdmitDate). Write queries to:

  1. Show patient names with their doctor's name
  2. Show the patients treated in the 'ENT' department
  3. Show each doctor's name with the number of patients
  4. Show the patients admitted after 30 June 2026.

Table: DOCTOR

DIDDNameDept
Columns only. The rows are given in the question paper.

Table: PATIENT

PIDPNameDIDAdmitDate
Columns only. The rows are given in the question paper.
Answer
SELECT PName, DName FROM PATIENT P, DOCTOR D WHERE P.DID = D.DID;
SELECT PName FROM PATIENT P, DOCTOR D WHERE P.DID = D.DID AND Dept = 'ENT';
SELECT DName, COUNT(*) FROM PATIENT P, DOCTOR D
  WHERE P.DID = D.DID GROUP BY DName;
SELECT * FROM PATIENT WHERE AdmitDate > '2026-06-30';
D3.8Practice4 marks

Tables BOOK (BNo, Title, Price) and ISSUE (BNo, MemberName, IssueDate). Write queries to:

  1. Show the title with the name of the member who took it
  2. Show the members who took books costing more than 300
  3. Show how many times each title was issued
  4. Delete the issue records dated before 1 January 2026.

Table: BOOK

BNoTitlePrice
Columns only. The rows are given in the question paper.

Table: ISSUE

BNoMemberNameIssueDate
Columns only. The rows are given in the question paper.
Answer
SELECT Title, MemberName FROM BOOK B, ISSUE I WHERE B.BNo = I.BNo;
SELECT MemberName FROM BOOK B, ISSUE I WHERE B.BNo = I.BNo AND Price > 300;
SELECT Title, COUNT(*) FROM BOOK B, ISSUE I
  WHERE B.BNo = I.BNo GROUP BY Title;
DELETE FROM ISSUE WHERE IssueDate < '2026-01-01';
D3.9Practice4 marks

Tables TEAM (TID, TName, City) and PLAYER (PID, PName, TID, Runs). Write queries to:

  1. Show player names with team names
  2. Show the total runs of each team
  3. Show the players of 'Chennai' teams who scored more than 500 runs
  4. Show the players in descending order of runs.

Table: TEAM

TIDTNameCity
Columns only. The rows are given in the question paper.

Table: PLAYER

PIDPNameTIDRuns
Columns only. The rows are given in the question paper.
Answer
SELECT PName, TName FROM PLAYER P, TEAM T WHERE P.TID = T.TID;
SELECT TName, SUM(Runs) FROM PLAYER P, TEAM T
  WHERE P.TID = T.TID GROUP BY TName;
SELECT PName FROM PLAYER P, TEAM T
  WHERE P.TID = T.TID AND City = 'Chennai' AND Runs > 500;
SELECT * FROM PLAYER ORDER BY Runs DESC;
D3.10Practice4 marks

Tables CUSTOMER (CID, CName, City) and ORDERS (ONo, CID, Amount, ODate). Write queries to:

  1. Show customer names with their order amounts
  2. Show the customers of 'Agra' who placed orders above 2000
  3. Show the number of orders of each customer
  4. Show all columns using a natural join.

Table: CUSTOMER

CIDCNameCity
Columns only. The rows are given in the question paper.

Table: ORDERS

ONoCIDAmountODate
Columns only. The rows are given in the question paper.
Answer
SELECT CName, Amount FROM CUSTOMER C, ORDERS O WHERE C.CID = O.CID;
SELECT CName FROM CUSTOMER C, ORDERS O
  WHERE C.CID = O.CID AND City = 'Agra' AND Amount > 2000;
SELECT CName, COUNT(*) FROM CUSTOMER C, ORDERS O
  WHERE C.CID = O.CID GROUP BY CName;
SELECT * FROM CUSTOMER NATURAL JOIN ORDERS;
D3.11Practice4 marks

Write SQL queries for the following, based on the tables DEPT and STAFF.

Table: DEPT

DNoDNameFloor
10Accounts1
20Sales2
30IT3

Table: STAFF

SNoSNameDNoPay
1Asha1042000
2Bilal2038000
3Chitra3065000
4Dev2041000
5Esha3058000
  1. Show each SName with its DName.
  2. Show the SName of the rows whose DName is 'IT'.
  3. Show each DName with the total Pay.
  4. Show all the columns of both tables using a natural join.
Answer
(i)
SELECT SName, DName FROM DEPT, STAFF
  WHERE DEPT.DNo = STAFF.DNo;
SNameDName
AshaAccounts
BilalSales
DevSales
ChitraIT
EshaIT

Explanation: The two tables DEPT and STAFF are joined: only the row pairs where DEPT.DNo = STAFF.DNo are kept (an equi-join). The join gives 5 rows.

(ii)
SELECT SName FROM DEPT, STAFF
  WHERE DEPT.DNo = STAFF.DNo AND DName = 'IT';
SName
Chitra
Esha

Explanation: The two tables DEPT and STAFF are joined: only the row pairs where DEPT.DNo = STAFF.DNo are kept (an equi-join). Of the 5 joined rows, 2 match the other condition: DName is 'IT'.

(iii)
SELECT DName, SUM(Pay) FROM DEPT, STAFF
  WHERE DEPT.DNo = STAFF.DNo GROUP BY DName;
DNameSUM(Pay)
Accounts42000
IT123000
Sales79000

Explanation: The two tables DEPT and STAFF are joined: only the row pairs where DEPT.DNo = STAFF.DNo are kept (an equi-join). The join gives 5 rows. GROUP BY DName makes 3 groups (Accounts, IT, Sales); the aggregate function is worked out separately for each group. SUM adds the values.

(iv)
SELECT * FROM DEPT NATURAL JOIN STAFF;
DNoDNameFloorSNoSNamePay
10Accounts11Asha42000
20Sales22Bilal38000
20Sales24Dev41000
30IT33Chitra65000
30IT35Esha58000

Explanation: NATURAL JOIN joins DEPT and STAFF on their common column, which is shown only once.

D3.12Practice4 marks

Write SQL queries for the following, based on the tables DEPT and STAFF.

Table: DEPT

DNoDNameFloor
10Accounts1
20Sales2
30IT3

Table: STAFF

SNoSNameDNoPay
1Asha1042000
2Bilal2038000
3Chitra3065000
4Dev2041000
5Esha3058000
  1. Show the Cartesian product of the two tables.
  2. Show the DName, SName and Pay where the Pay is more than 40000.
  3. Show each DName with the number of rows it has in STAFF.
  4. Show the rows of STAFF in descending order of Pay.
Answer
(i)
SELECT * FROM DEPT, STAFF;

Output: 15 rows and 7 columns.

Explanation: With no join condition the result is the Cartesian product: 3 × 5 = 15 row pairs.

(ii)
SELECT DName, SName, Pay FROM DEPT, STAFF
  WHERE DEPT.DNo = STAFF.DNo AND Pay > 40000;
DNameSNamePay
AccountsAsha42000
ITChitra65000
SalesDev41000
ITEsha58000

Explanation: The two tables DEPT and STAFF are joined: only the row pairs where DEPT.DNo = STAFF.DNo are kept (an equi-join). Of the 5 joined rows, 4 match the other condition: Pay is more than 40000.

(iii)
SELECT DName, COUNT(*) FROM DEPT, STAFF
  WHERE DEPT.DNo = STAFF.DNo GROUP BY DName;
DNameCOUNT(*)
Accounts1
IT2
Sales2

Explanation: The two tables DEPT and STAFF are joined: only the row pairs where DEPT.DNo = STAFF.DNo are kept (an equi-join). The join gives 5 rows. GROUP BY DName makes 3 groups (Accounts, IT, Sales); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iv)
SELECT * FROM STAFF ORDER BY Pay DESC;
SNoSNameDNoPay
3Chitra3065000
5Esha3058000
1Asha1042000
4Dev2041000
2Bilal2038000

Explanation: ORDER BY Pay arranges the result in descending (largest first) order.

D3.13Practice4 marks

Write SQL queries for the following, based on the tables DEPT and STAFF.

Table: DEPT

DNoDNameFloor
10Accounts1
20Sales2
30IT3

Table: STAFF

SNoSNameDNoPay
1Asha1042000
2Bilal2038000
3Chitra3065000
4Dev2041000
5Esha3058000
  1. Show the SName and DName where the Pay is from 40000 to 60000.
  2. Show each DName with the highest Pay.
  3. Increase the Pay by 1000 in the rows of STAFF whose DNo is 20.
  4. Show the DName and SName in ascending order of SName.
Answer
(i)
SELECT SName, DName FROM DEPT, STAFF
  WHERE DEPT.DNo = STAFF.DNo AND Pay BETWEEN 40000 AND 60000;
SNameDName
AshaAccounts
DevSales
EshaIT

Explanation: The two tables DEPT and STAFF are joined: only the row pairs where DEPT.DNo = STAFF.DNo are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Pay is from 40000 to 60000 (both included).

(ii)
SELECT DName, MAX(Pay) FROM DEPT, STAFF
  WHERE DEPT.DNo = STAFF.DNo GROUP BY DName;
DNameMAX(Pay)
Accounts42000
IT65000
Sales41000

Explanation: The two tables DEPT and STAFF are joined: only the row pairs where DEPT.DNo = STAFF.DNo are kept (an equi-join). The join gives 5 rows. GROUP BY DName makes 3 groups (Accounts, IT, Sales); the aggregate function is worked out separately for each group. MAX gives the largest value.

(iii)
UPDATE STAFF SET Pay = Pay + 1000 WHERE DNo = 20;

2 rows changed.

Explanation: SET Pay = Pay + 1000 changes the value; WHERE limits the change to the rows where DNo is 20: 2 rows changed.

(iv)
SELECT DName, SName FROM DEPT, STAFF
  WHERE DEPT.DNo = STAFF.DNo ORDER BY SName;
DNameSName
AccountsAsha
SalesBilal
ITChitra
SalesDev
ITEsha

Explanation: The two tables DEPT and STAFF are joined: only the row pairs where DEPT.DNo = STAFF.DNo are kept (an equi-join). The join gives 5 rows. ORDER BY SName arranges the result in ascending (smallest first) order.

D3.14Practice4 marks

Write SQL queries for the following, based on the tables CLASS and PUPIL.

Table: CLASS

CNoCNameTeacher
11XI-AMr Rao
12XI-BMs Sen
13XII-AMr Khan

Table: PUPIL

RNoPNameCNoMarks
1Aman1178
2Bina1291
3Chirag1366
4Diya1185
5Farid1372
  1. Show each PName with its CName.
  2. Show the PName of the rows whose CName is 'XI-A'.
  3. Show each CName with the total Marks.
  4. Show all the columns of both tables using a natural join.
Answer
(i)
SELECT PName, CName FROM CLASS, PUPIL
  WHERE CLASS.CNo = PUPIL.CNo;
PNameCName
AmanXI-A
DiyaXI-A
BinaXI-B
ChiragXII-A
FaridXII-A

Explanation: The two tables CLASS and PUPIL are joined: only the row pairs where CLASS.CNo = PUPIL.CNo are kept (an equi-join). The join gives 5 rows.

(ii)
SELECT PName FROM CLASS, PUPIL
  WHERE CLASS.CNo = PUPIL.CNo AND CName = 'XI-A';
PName
Aman
Diya

Explanation: The two tables CLASS and PUPIL are joined: only the row pairs where CLASS.CNo = PUPIL.CNo are kept (an equi-join). Of the 5 joined rows, 2 match the other condition: CName is 'XI-A'.

(iii)
SELECT CName, SUM(Marks) FROM CLASS, PUPIL
  WHERE CLASS.CNo = PUPIL.CNo GROUP BY CName;
CNameSUM(Marks)
XI-A163
XI-B91
XII-A138

Explanation: The two tables CLASS and PUPIL are joined: only the row pairs where CLASS.CNo = PUPIL.CNo are kept (an equi-join). The join gives 5 rows. GROUP BY CName makes 3 groups (XI-A, XI-B, XII-A); the aggregate function is worked out separately for each group. SUM adds the values.

(iv)
SELECT * FROM CLASS NATURAL JOIN PUPIL;
CNoCNameTeacherRNoPNameMarks
11XI-AMr Rao1Aman78
11XI-AMr Rao4Diya85
12XI-BMs Sen2Bina91
13XII-AMr Khan3Chirag66
13XII-AMr Khan5Farid72

Explanation: NATURAL JOIN joins CLASS and PUPIL on their common column, which is shown only once.

D3.15Practice4 marks

Write SQL queries for the following, based on the tables CLASS and PUPIL.

Table: CLASS

CNoCNameTeacher
11XI-AMr Rao
12XI-BMs Sen
13XII-AMr Khan

Table: PUPIL

RNoPNameCNoMarks
1Aman1178
2Bina1291
3Chirag1366
4Diya1185
5Farid1372
  1. Show the Cartesian product of the two tables.
  2. Show the CName, PName and Marks where the Marks is more than 75.
  3. Show each CName with the number of rows it has in PUPIL.
  4. Show the rows of PUPIL in descending order of Marks.
Answer
(i)
SELECT * FROM CLASS, PUPIL;

Output: 15 rows and 7 columns.

Explanation: With no join condition the result is the Cartesian product: 3 × 5 = 15 row pairs.

(ii)
SELECT CName, PName, Marks FROM CLASS, PUPIL
  WHERE CLASS.CNo = PUPIL.CNo AND Marks > 75;
CNamePNameMarks
XI-AAman78
XI-BBina91
XI-ADiya85

Explanation: The two tables CLASS and PUPIL are joined: only the row pairs where CLASS.CNo = PUPIL.CNo are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Marks is more than 75.

(iii)
SELECT CName, COUNT(*) FROM CLASS, PUPIL
  WHERE CLASS.CNo = PUPIL.CNo GROUP BY CName;
CNameCOUNT(*)
XI-A2
XI-B1
XII-A2

Explanation: The two tables CLASS and PUPIL are joined: only the row pairs where CLASS.CNo = PUPIL.CNo are kept (an equi-join). The join gives 5 rows. GROUP BY CName makes 3 groups (XI-A, XI-B, XII-A); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iv)
SELECT * FROM PUPIL ORDER BY Marks DESC;
RNoPNameCNoMarks
2Bina1291
4Diya1185
1Aman1178
5Farid1372
3Chirag1366

Explanation: ORDER BY Marks arranges the result in descending (largest first) order.

D3.16Practice4 marks

Write SQL queries for the following, based on the tables CLASS and PUPIL.

Table: CLASS

CNoCNameTeacher
11XI-AMr Rao
12XI-BMs Sen
13XII-AMr Khan

Table: PUPIL

RNoPNameCNoMarks
1Aman1178
2Bina1291
3Chirag1366
4Diya1185
5Farid1372
  1. Show the PName and CName where the Marks is from 70 to 90.
  2. Show each CName with the highest Marks.
  3. Increase the Marks by 5 in the rows of PUPIL whose CNo is 13.
  4. Show the CName and PName in ascending order of PName.
Answer
(i)
SELECT PName, CName FROM CLASS, PUPIL
  WHERE CLASS.CNo = PUPIL.CNo AND Marks BETWEEN 70 AND 90;
PNameCName
AmanXI-A
DiyaXI-A
FaridXII-A

Explanation: The two tables CLASS and PUPIL are joined: only the row pairs where CLASS.CNo = PUPIL.CNo are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Marks is from 70 to 90 (both included).

(ii)
SELECT CName, MAX(Marks) FROM CLASS, PUPIL
  WHERE CLASS.CNo = PUPIL.CNo GROUP BY CName;
CNameMAX(Marks)
XI-A85
XI-B91
XII-A72

Explanation: The two tables CLASS and PUPIL are joined: only the row pairs where CLASS.CNo = PUPIL.CNo are kept (an equi-join). The join gives 5 rows. GROUP BY CName makes 3 groups (XI-A, XI-B, XII-A); the aggregate function is worked out separately for each group. MAX gives the largest value.

(iii)
UPDATE PUPIL SET Marks = Marks + 5 WHERE CNo = 13;

2 rows changed.

Explanation: SET Marks = Marks + 5 changes the value; WHERE limits the change to the rows where CNo is 13: 2 rows changed.

(iv)
SELECT CName, PName FROM CLASS, PUPIL
  WHERE CLASS.CNo = PUPIL.CNo ORDER BY PName;
CNamePName
XI-AAman
XI-BBina
XII-AChirag
XI-ADiya
XII-AFarid

Explanation: The two tables CLASS and PUPIL are joined: only the row pairs where CLASS.CNo = PUPIL.CNo are kept (an equi-join). The join gives 5 rows. ORDER BY PName arranges the result in ascending (smallest first) order.

D3.17Practice4 marks

Write SQL queries for the following, based on the tables SHOP and SALE.

Table: SHOP

SIDSNameArea
1Fresh MartRohini
2City StoreDwarka
3Daily NeedsSaket

Table: SALE

BillNoSIDItemAmount
5011Rice1200
5022Oil850
5031Sugar400
5043Tea300
5052Atta950
  1. Show each Item with its SName.
  2. Show the Item of the rows whose Area is 'Dwarka'.
  3. Show each SName with the total Amount.
  4. Show all the columns of both tables using a natural join.
Answer
(i)
SELECT Item, SName FROM SHOP, SALE
  WHERE SHOP.SID = SALE.SID;
ItemSName
RiceFresh Mart
SugarFresh Mart
AttaCity Store
OilCity Store
TeaDaily Needs

Explanation: The two tables SHOP and SALE are joined: only the row pairs where SHOP.SID = SALE.SID are kept (an equi-join). The join gives 5 rows.

(ii)
SELECT Item FROM SHOP, SALE
  WHERE SHOP.SID = SALE.SID AND Area = 'Dwarka';
Item
Atta
Oil

Explanation: The two tables SHOP and SALE are joined: only the row pairs where SHOP.SID = SALE.SID are kept (an equi-join). Of the 5 joined rows, 2 match the other condition: Area is 'Dwarka'.

(iii)
SELECT SName, SUM(Amount) FROM SHOP, SALE
  WHERE SHOP.SID = SALE.SID GROUP BY SName;
SNameSUM(Amount)
City Store1800
Daily Needs300
Fresh Mart1600

Explanation: The two tables SHOP and SALE are joined: only the row pairs where SHOP.SID = SALE.SID are kept (an equi-join). The join gives 5 rows. GROUP BY SName makes 3 groups (City Store, Daily Needs, Fresh Mart); the aggregate function is worked out separately for each group. SUM adds the values.

(iv)
SELECT * FROM SHOP NATURAL JOIN SALE;
SIDSNameAreaBillNoItemAmount
1Fresh MartRohini501Rice1200
1Fresh MartRohini503Sugar400
2City StoreDwarka502Oil850
2City StoreDwarka505Atta950
3Daily NeedsSaket504Tea300

Explanation: NATURAL JOIN joins SHOP and SALE on their common column, which is shown only once.

D3.18Practice4 marks

Write SQL queries for the following, based on the tables SHOP and SALE.

Table: SHOP

SIDSNameArea
1Fresh MartRohini
2City StoreDwarka
3Daily NeedsSaket

Table: SALE

BillNoSIDItemAmount
5011Rice1200
5022Oil850
5031Sugar400
5043Tea300
5052Atta950
  1. Show the Cartesian product of the two tables.
  2. Show the SName, Item and Amount where the Amount is more than 800.
  3. Show each SName with the number of rows it has in SALE.
  4. Show the rows of SALE in descending order of Amount.
Answer
(i)
SELECT * FROM SHOP, SALE;

Output: 15 rows and 7 columns.

Explanation: With no join condition the result is the Cartesian product: 3 × 5 = 15 row pairs.

(ii)
SELECT SName, Item, Amount FROM SHOP, SALE
  WHERE SHOP.SID = SALE.SID AND Amount > 800;
SNameItemAmount
Fresh MartRice1200
City StoreOil850
City StoreAtta950

Explanation: The two tables SHOP and SALE are joined: only the row pairs where SHOP.SID = SALE.SID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Amount is more than 800.

(iii)
SELECT SName, COUNT(*) FROM SHOP, SALE
  WHERE SHOP.SID = SALE.SID GROUP BY SName;
SNameCOUNT(*)
City Store2
Daily Needs1
Fresh Mart2

Explanation: The two tables SHOP and SALE are joined: only the row pairs where SHOP.SID = SALE.SID are kept (an equi-join). The join gives 5 rows. GROUP BY SName makes 3 groups (City Store, Daily Needs, Fresh Mart); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iv)
SELECT * FROM SALE ORDER BY Amount DESC;
BillNoSIDItemAmount
5011Rice1200
5052Atta950
5022Oil850
5031Sugar400
5043Tea300

Explanation: ORDER BY Amount arranges the result in descending (largest first) order.

D3.19Practice4 marks

Write SQL queries for the following, based on the tables SHOP and SALE.

Table: SHOP

SIDSNameArea
1Fresh MartRohini
2City StoreDwarka
3Daily NeedsSaket

Table: SALE

BillNoSIDItemAmount
5011Rice1200
5022Oil850
5031Sugar400
5043Tea300
5052Atta950
  1. Show the Item and SName where the Amount is from 400 to 1000.
  2. Show each SName with the highest Amount.
  3. Increase the Amount by 50 in the rows of SALE whose SID is 1.
  4. Show the SName and Item in ascending order of Item.
Answer
(i)
SELECT Item, SName FROM SHOP, SALE
  WHERE SHOP.SID = SALE.SID AND Amount BETWEEN 400 AND 1000;
ItemSName
OilCity Store
SugarFresh Mart
AttaCity Store

Explanation: The two tables SHOP and SALE are joined: only the row pairs where SHOP.SID = SALE.SID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Amount is from 400 to 1000 (both included).

(ii)
SELECT SName, MAX(Amount) FROM SHOP, SALE
  WHERE SHOP.SID = SALE.SID GROUP BY SName;
SNameMAX(Amount)
City Store950
Daily Needs300
Fresh Mart1200

Explanation: The two tables SHOP and SALE are joined: only the row pairs where SHOP.SID = SALE.SID are kept (an equi-join). The join gives 5 rows. GROUP BY SName makes 3 groups (City Store, Daily Needs, Fresh Mart); the aggregate function is worked out separately for each group. MAX gives the largest value.

(iii)
UPDATE SALE SET Amount = Amount + 50 WHERE SID = 1;

2 rows changed.

Explanation: SET Amount = Amount + 50 changes the value; WHERE limits the change to the rows where SID is 1: 2 rows changed.

(iv)
SELECT SName, Item FROM SHOP, SALE
  WHERE SHOP.SID = SALE.SID ORDER BY Item;
SNameItem
City StoreAtta
City StoreOil
Fresh MartRice
Fresh MartSugar
Daily NeedsTea

Explanation: The two tables SHOP and SALE are joined: only the row pairs where SHOP.SID = SALE.SID are kept (an equi-join). The join gives 5 rows. ORDER BY Item arranges the result in ascending (smallest first) order.

D3.20Practice4 marks

Write SQL queries for the following, based on the tables AUTHOR and NOVEL.

Table: AUTHOR

AIDANameCountry
1R. MehtaIndia
2J. CarterUSA
3S. IyerIndia

Table: NOVEL

NIDTitleAIDPrice
101Blue Sky1350
102Lost Map2499
103Green Hill1275
104River Song3420
105Night Train2560
  1. Show each Title with its AName.
  2. Show the Title of the rows whose Country is 'India'.
  3. Show each AName with the total Price.
  4. Show all the columns of both tables using a natural join.
Answer
(i)
SELECT Title, AName FROM AUTHOR, NOVEL
  WHERE AUTHOR.AID = NOVEL.AID;
TitleAName
Blue SkyR. Mehta
Green HillR. Mehta
Lost MapJ. Carter
Night TrainJ. Carter
River SongS. Iyer

Explanation: The two tables AUTHOR and NOVEL are joined: only the row pairs where AUTHOR.AID = NOVEL.AID are kept (an equi-join). The join gives 5 rows.

(ii)
SELECT Title FROM AUTHOR, NOVEL
  WHERE AUTHOR.AID = NOVEL.AID AND Country = 'India';
Title
Blue Sky
Green Hill
River Song

Explanation: The two tables AUTHOR and NOVEL are joined: only the row pairs where AUTHOR.AID = NOVEL.AID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Country is 'India'.

(iii)
SELECT AName, SUM(Price) FROM AUTHOR, NOVEL
  WHERE AUTHOR.AID = NOVEL.AID GROUP BY AName;
ANameSUM(Price)
J. Carter1059
R. Mehta625
S. Iyer420

Explanation: The two tables AUTHOR and NOVEL are joined: only the row pairs where AUTHOR.AID = NOVEL.AID are kept (an equi-join). The join gives 5 rows. GROUP BY AName makes 3 groups (J. Carter, R. Mehta, S. Iyer); the aggregate function is worked out separately for each group. SUM adds the values.

(iv)
SELECT * FROM AUTHOR NATURAL JOIN NOVEL;
AIDANameCountryNIDTitlePrice
1R. MehtaIndia101Blue Sky350
1R. MehtaIndia103Green Hill275
2J. CarterUSA102Lost Map499
2J. CarterUSA105Night Train560
3S. IyerIndia104River Song420

Explanation: NATURAL JOIN joins AUTHOR and NOVEL on their common column, which is shown only once.

D3.21Practice4 marks

Write SQL queries for the following, based on the tables AUTHOR and NOVEL.

Table: AUTHOR

AIDANameCountry
1R. MehtaIndia
2J. CarterUSA
3S. IyerIndia

Table: NOVEL

NIDTitleAIDPrice
101Blue Sky1350
102Lost Map2499
103Green Hill1275
104River Song3420
105Night Train2560
  1. Show the Cartesian product of the two tables.
  2. Show the AName, Title and Price where the Price is more than 400.
  3. Show each AName with the number of rows it has in NOVEL.
  4. Show the rows of NOVEL in descending order of Price.
Answer
(i)
SELECT * FROM AUTHOR, NOVEL;

Output: 15 rows and 7 columns.

Explanation: With no join condition the result is the Cartesian product: 3 × 5 = 15 row pairs.

(ii)
SELECT AName, Title, Price FROM AUTHOR, NOVEL
  WHERE AUTHOR.AID = NOVEL.AID AND Price > 400;
ANameTitlePrice
J. CarterLost Map499
S. IyerRiver Song420
J. CarterNight Train560

Explanation: The two tables AUTHOR and NOVEL are joined: only the row pairs where AUTHOR.AID = NOVEL.AID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Price is more than 400.

(iii)
SELECT AName, COUNT(*) FROM AUTHOR, NOVEL
  WHERE AUTHOR.AID = NOVEL.AID GROUP BY AName;
ANameCOUNT(*)
J. Carter2
R. Mehta2
S. Iyer1

Explanation: The two tables AUTHOR and NOVEL are joined: only the row pairs where AUTHOR.AID = NOVEL.AID are kept (an equi-join). The join gives 5 rows. GROUP BY AName makes 3 groups (J. Carter, R. Mehta, S. Iyer); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iv)
SELECT * FROM NOVEL ORDER BY Price DESC;
NIDTitleAIDPrice
105Night Train2560
102Lost Map2499
104River Song3420
101Blue Sky1350
103Green Hill1275

Explanation: ORDER BY Price arranges the result in descending (largest first) order.

D3.22Practice4 marks

Write SQL queries for the following, based on the tables AUTHOR and NOVEL.

Table: AUTHOR

AIDANameCountry
1R. MehtaIndia
2J. CarterUSA
3S. IyerIndia

Table: NOVEL

NIDTitleAIDPrice
101Blue Sky1350
102Lost Map2499
103Green Hill1275
104River Song3420
105Night Train2560
  1. Show the Title and AName where the Price is from 300 to 500.
  2. Show each AName with the highest Price.
  3. Increase the Price by 25 in the rows of NOVEL whose AID is 2.
  4. Show the AName and Title in ascending order of Title.
Answer
(i)
SELECT Title, AName FROM AUTHOR, NOVEL
  WHERE AUTHOR.AID = NOVEL.AID AND Price BETWEEN 300 AND 500;
TitleAName
Blue SkyR. Mehta
Lost MapJ. Carter
River SongS. Iyer

Explanation: The two tables AUTHOR and NOVEL are joined: only the row pairs where AUTHOR.AID = NOVEL.AID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Price is from 300 to 500 (both included).

(ii)
SELECT AName, MAX(Price) FROM AUTHOR, NOVEL
  WHERE AUTHOR.AID = NOVEL.AID GROUP BY AName;
ANameMAX(Price)
J. Carter560
R. Mehta350
S. Iyer420

Explanation: The two tables AUTHOR and NOVEL are joined: only the row pairs where AUTHOR.AID = NOVEL.AID are kept (an equi-join). The join gives 5 rows. GROUP BY AName makes 3 groups (J. Carter, R. Mehta, S. Iyer); the aggregate function is worked out separately for each group. MAX gives the largest value.

(iii)
UPDATE NOVEL SET Price = Price + 25 WHERE AID = 2;

2 rows changed.

Explanation: SET Price = Price + 25 changes the value; WHERE limits the change to the rows where AID is 2: 2 rows changed.

(iv)
SELECT AName, Title FROM AUTHOR, NOVEL
  WHERE AUTHOR.AID = NOVEL.AID ORDER BY Title;
ANameTitle
R. MehtaBlue Sky
R. MehtaGreen Hill
J. CarterLost Map
J. CarterNight Train
S. IyerRiver Song

Explanation: The two tables AUTHOR and NOVEL are joined: only the row pairs where AUTHOR.AID = NOVEL.AID are kept (an equi-join). The join gives 5 rows. ORDER BY Title arranges the result in ascending (smallest first) order.

D3.23Practice4 marks

Write SQL queries for the following, based on the tables ROUTE and TRIP.

Table: ROUTE

RIDCityDistance
1Jaipur280
2Agra230
3Shimla350

Table: TRIP

TIDRIDDriverFare
11Hari900
22Iqbal750
31Joseph950
43Kamal1400
52Hari800
  1. Show each Driver with its City.
  2. Show the Driver of the rows whose City is 'Agra'.
  3. Show each City with the total Fare.
  4. Show all the columns of both tables using a natural join.
Answer
(i)
SELECT Driver, City FROM ROUTE, TRIP
  WHERE ROUTE.RID = TRIP.RID;
DriverCity
HariJaipur
JosephJaipur
HariAgra
IqbalAgra
KamalShimla

Explanation: The two tables ROUTE and TRIP are joined: only the row pairs where ROUTE.RID = TRIP.RID are kept (an equi-join). The join gives 5 rows.

(ii)
SELECT Driver FROM ROUTE, TRIP
  WHERE ROUTE.RID = TRIP.RID AND City = 'Agra';
Driver
Hari
Iqbal

Explanation: The two tables ROUTE and TRIP are joined: only the row pairs where ROUTE.RID = TRIP.RID are kept (an equi-join). Of the 5 joined rows, 2 match the other condition: City is 'Agra'.

(iii)
SELECT City, SUM(Fare) FROM ROUTE, TRIP
  WHERE ROUTE.RID = TRIP.RID GROUP BY City;
CitySUM(Fare)
Agra1550
Jaipur1850
Shimla1400

Explanation: The two tables ROUTE and TRIP are joined: only the row pairs where ROUTE.RID = TRIP.RID are kept (an equi-join). The join gives 5 rows. GROUP BY City makes 3 groups (Agra, Jaipur, Shimla); the aggregate function is worked out separately for each group. SUM adds the values.

(iv)
SELECT * FROM ROUTE NATURAL JOIN TRIP;
RIDCityDistanceTIDDriverFare
1Jaipur2801Hari900
1Jaipur2803Joseph950
2Agra2302Iqbal750
2Agra2305Hari800
3Shimla3504Kamal1400

Explanation: NATURAL JOIN joins ROUTE and TRIP on their common column, which is shown only once.

D3.24Practice4 marks

Write SQL queries for the following, based on the tables ROUTE and TRIP.

Table: ROUTE

RIDCityDistance
1Jaipur280
2Agra230
3Shimla350

Table: TRIP

TIDRIDDriverFare
11Hari900
22Iqbal750
31Joseph950
43Kamal1400
52Hari800
  1. Show the Cartesian product of the two tables.
  2. Show the City, Driver and Fare where the Fare is more than 850.
  3. Show each City with the number of rows it has in TRIP.
  4. Show the rows of TRIP in descending order of Fare.
Answer
(i)
SELECT * FROM ROUTE, TRIP;

Output: 15 rows and 7 columns.

Explanation: With no join condition the result is the Cartesian product: 3 × 5 = 15 row pairs.

(ii)
SELECT City, Driver, Fare FROM ROUTE, TRIP
  WHERE ROUTE.RID = TRIP.RID AND Fare > 850;
CityDriverFare
JaipurHari900
JaipurJoseph950
ShimlaKamal1400

Explanation: The two tables ROUTE and TRIP are joined: only the row pairs where ROUTE.RID = TRIP.RID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Fare is more than 850.

(iii)
SELECT City, COUNT(*) FROM ROUTE, TRIP
  WHERE ROUTE.RID = TRIP.RID GROUP BY City;
CityCOUNT(*)
Agra2
Jaipur2
Shimla1

Explanation: The two tables ROUTE and TRIP are joined: only the row pairs where ROUTE.RID = TRIP.RID are kept (an equi-join). The join gives 5 rows. GROUP BY City makes 3 groups (Agra, Jaipur, Shimla); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iv)
SELECT * FROM TRIP ORDER BY Fare DESC;
TIDRIDDriverFare
43Kamal1400
31Joseph950
11Hari900
52Hari800
22Iqbal750

Explanation: ORDER BY Fare arranges the result in descending (largest first) order.

D3.25Practice4 marks

Write SQL queries for the following, based on the tables ROUTE and TRIP.

Table: ROUTE

RIDCityDistance
1Jaipur280
2Agra230
3Shimla350

Table: TRIP

TIDRIDDriverFare
11Hari900
22Iqbal750
31Joseph950
43Kamal1400
52Hari800
  1. Show the Driver and City where the Fare is from 800 to 1000.
  2. Show each City with the highest Fare.
  3. Increase the Fare by 100 in the rows of TRIP whose RID is 3.
  4. Show the City and Driver in ascending order of Driver.
Answer
(i)
SELECT Driver, City FROM ROUTE, TRIP
  WHERE ROUTE.RID = TRIP.RID AND Fare BETWEEN 800 AND 1000;
DriverCity
HariJaipur
JosephJaipur
HariAgra

Explanation: The two tables ROUTE and TRIP are joined: only the row pairs where ROUTE.RID = TRIP.RID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Fare is from 800 to 1000 (both included).

(ii)
SELECT City, MAX(Fare) FROM ROUTE, TRIP
  WHERE ROUTE.RID = TRIP.RID GROUP BY City;
CityMAX(Fare)
Agra800
Jaipur950
Shimla1400

Explanation: The two tables ROUTE and TRIP are joined: only the row pairs where ROUTE.RID = TRIP.RID are kept (an equi-join). The join gives 5 rows. GROUP BY City makes 3 groups (Agra, Jaipur, Shimla); the aggregate function is worked out separately for each group. MAX gives the largest value.

(iii)
UPDATE TRIP SET Fare = Fare + 100 WHERE RID = 3;

1 row changed.

Explanation: SET Fare = Fare + 100 changes the value; WHERE limits the change to the rows where RID is 3: 1 row changed.

(iv)
SELECT City, Driver FROM ROUTE, TRIP
  WHERE ROUTE.RID = TRIP.RID ORDER BY Driver;
CityDriver
JaipurHari
AgraHari
AgraIqbal
JaipurJoseph
ShimlaKamal

Explanation: The two tables ROUTE and TRIP are joined: only the row pairs where ROUTE.RID = TRIP.RID are kept (an equi-join). The join gives 5 rows. ORDER BY Driver arranges the result in ascending (smallest first) order.

D3.26Practice4 marks

Write SQL queries for the following, based on the tables HOUSE and MEMBER.

Table: HOUSE

HIDHNameColour
1ShivajiRed
2TagoreBlue
3RamanGreen

Table: MEMBER

MIDMNameHIDPoints
1Neha145
2Om260
3Pari338
4Qasim172
5Rhea255
  1. Show each MName with its HName.
  2. Show the MName of the rows whose Colour is 'Blue'.
  3. Show each HName with the total Points.
  4. Show all the columns of both tables using a natural join.
Answer
(i)
SELECT MName, HName FROM HOUSE, MEMBER
  WHERE HOUSE.HID = MEMBER.HID;
MNameHName
NehaShivaji
QasimShivaji
OmTagore
RheaTagore
PariRaman

Explanation: The two tables HOUSE and MEMBER are joined: only the row pairs where HOUSE.HID = MEMBER.HID are kept (an equi-join). The join gives 5 rows.

(ii)
SELECT MName FROM HOUSE, MEMBER
  WHERE HOUSE.HID = MEMBER.HID AND Colour = 'Blue';
MName
Om
Rhea

Explanation: The two tables HOUSE and MEMBER are joined: only the row pairs where HOUSE.HID = MEMBER.HID are kept (an equi-join). Of the 5 joined rows, 2 match the other condition: Colour is 'Blue'.

(iii)
SELECT HName, SUM(Points) FROM HOUSE, MEMBER
  WHERE HOUSE.HID = MEMBER.HID GROUP BY HName;
HNameSUM(Points)
Raman38
Shivaji117
Tagore115

Explanation: The two tables HOUSE and MEMBER are joined: only the row pairs where HOUSE.HID = MEMBER.HID are kept (an equi-join). The join gives 5 rows. GROUP BY HName makes 3 groups (Raman, Shivaji, Tagore); the aggregate function is worked out separately for each group. SUM adds the values.

(iv)
SELECT * FROM HOUSE NATURAL JOIN MEMBER;
HIDHNameColourMIDMNamePoints
1ShivajiRed1Neha45
1ShivajiRed4Qasim72
2TagoreBlue2Om60
2TagoreBlue5Rhea55
3RamanGreen3Pari38

Explanation: NATURAL JOIN joins HOUSE and MEMBER on their common column, which is shown only once.

D3.27Practice4 marks

Write SQL queries for the following, based on the tables HOUSE and MEMBER.

Table: HOUSE

HIDHNameColour
1ShivajiRed
2TagoreBlue
3RamanGreen

Table: MEMBER

MIDMNameHIDPoints
1Neha145
2Om260
3Pari338
4Qasim172
5Rhea255
  1. Show the Cartesian product of the two tables.
  2. Show the HName, MName and Points where the Points is more than 50.
  3. Show each HName with the number of rows it has in MEMBER.
  4. Show the rows of MEMBER in descending order of Points.
Answer
(i)
SELECT * FROM HOUSE, MEMBER;

Output: 15 rows and 7 columns.

Explanation: With no join condition the result is the Cartesian product: 3 × 5 = 15 row pairs.

(ii)
SELECT HName, MName, Points FROM HOUSE, MEMBER
  WHERE HOUSE.HID = MEMBER.HID AND Points > 50;
HNameMNamePoints
TagoreOm60
ShivajiQasim72
TagoreRhea55

Explanation: The two tables HOUSE and MEMBER are joined: only the row pairs where HOUSE.HID = MEMBER.HID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Points is more than 50.

(iii)
SELECT HName, COUNT(*) FROM HOUSE, MEMBER
  WHERE HOUSE.HID = MEMBER.HID GROUP BY HName;
HNameCOUNT(*)
Raman1
Shivaji2
Tagore2

Explanation: The two tables HOUSE and MEMBER are joined: only the row pairs where HOUSE.HID = MEMBER.HID are kept (an equi-join). The join gives 5 rows. GROUP BY HName makes 3 groups (Raman, Shivaji, Tagore); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iv)
SELECT * FROM MEMBER ORDER BY Points DESC;
MIDMNameHIDPoints
4Qasim172
2Om260
5Rhea255
1Neha145
3Pari338

Explanation: ORDER BY Points arranges the result in descending (largest first) order.

D3.28Practice4 marks

Write SQL queries for the following, based on the tables HOUSE and MEMBER.

Table: HOUSE

HIDHNameColour
1ShivajiRed
2TagoreBlue
3RamanGreen

Table: MEMBER

MIDMNameHIDPoints
1Neha145
2Om260
3Pari338
4Qasim172
5Rhea255
  1. Show the MName and HName where the Points is from 40 to 60.
  2. Show each HName with the highest Points.
  3. Increase the Points by 10 in the rows of MEMBER whose HID is 3.
  4. Show the HName and MName in ascending order of MName.
Answer
(i)
SELECT MName, HName FROM HOUSE, MEMBER
  WHERE HOUSE.HID = MEMBER.HID AND Points BETWEEN 40 AND 60;
MNameHName
NehaShivaji
OmTagore
RheaTagore

Explanation: The two tables HOUSE and MEMBER are joined: only the row pairs where HOUSE.HID = MEMBER.HID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Points is from 40 to 60 (both included).

(ii)
SELECT HName, MAX(Points) FROM HOUSE, MEMBER
  WHERE HOUSE.HID = MEMBER.HID GROUP BY HName;
HNameMAX(Points)
Raman38
Shivaji72
Tagore60

Explanation: The two tables HOUSE and MEMBER are joined: only the row pairs where HOUSE.HID = MEMBER.HID are kept (an equi-join). The join gives 5 rows. GROUP BY HName makes 3 groups (Raman, Shivaji, Tagore); the aggregate function is worked out separately for each group. MAX gives the largest value.

(iii)
UPDATE MEMBER SET Points = Points + 10 WHERE HID = 3;

1 row changed.

Explanation: SET Points = Points + 10 changes the value; WHERE limits the change to the rows where HID is 3: 1 row changed.

(iv)
SELECT HName, MName FROM HOUSE, MEMBER
  WHERE HOUSE.HID = MEMBER.HID ORDER BY MName;
HNameMName
ShivajiNeha
TagoreOm
RamanPari
ShivajiQasim
TagoreRhea

Explanation: The two tables HOUSE and MEMBER are joined: only the row pairs where HOUSE.HID = MEMBER.HID are kept (an equi-join). The join gives 5 rows. ORDER BY MName arranges the result in ascending (smallest first) order.

D3.29Practice4 marks

Write SQL queries for the following, based on the tables LAB and COMPUTER.

Table: LAB

LIDLNameIncharge
1Junior LabMs Roy
2Senior LabMr Das
3AI LabMs Paul

Table: COMPUTER

CompNoLIDBrandRAM
11Zenbook8
22Orbit16
32Zenbook8
43Lumo32
53Orbit16
  1. Show each Brand with its LName.
  2. Show the Brand of the rows whose LName is 'AI Lab'.
  3. Show each LName with the total RAM.
  4. Show all the columns of both tables using a natural join.
Answer
(i)
SELECT Brand, LName FROM LAB, COMPUTER
  WHERE LAB.LID = COMPUTER.LID;
BrandLName
ZenbookJunior Lab
OrbitSenior Lab
ZenbookSenior Lab
LumoAI Lab
OrbitAI Lab

Explanation: The two tables LAB and COMPUTER are joined: only the row pairs where LAB.LID = COMPUTER.LID are kept (an equi-join). The join gives 5 rows.

(ii)
SELECT Brand FROM LAB, COMPUTER
  WHERE LAB.LID = COMPUTER.LID AND LName = 'AI Lab';
Brand
Lumo
Orbit

Explanation: The two tables LAB and COMPUTER are joined: only the row pairs where LAB.LID = COMPUTER.LID are kept (an equi-join). Of the 5 joined rows, 2 match the other condition: LName is 'AI Lab'.

(iii)
SELECT LName, SUM(RAM) FROM LAB, COMPUTER
  WHERE LAB.LID = COMPUTER.LID GROUP BY LName;
LNameSUM(RAM)
AI Lab48
Junior Lab8
Senior Lab24

Explanation: The two tables LAB and COMPUTER are joined: only the row pairs where LAB.LID = COMPUTER.LID are kept (an equi-join). The join gives 5 rows. GROUP BY LName makes 3 groups (AI Lab, Junior Lab, Senior Lab); the aggregate function is worked out separately for each group. SUM adds the values.

(iv)
SELECT * FROM LAB NATURAL JOIN COMPUTER;
LIDLNameInchargeCompNoBrandRAM
1Junior LabMs Roy1Zenbook8
2Senior LabMr Das2Orbit16
2Senior LabMr Das3Zenbook8
3AI LabMs Paul4Lumo32
3AI LabMs Paul5Orbit16

Explanation: NATURAL JOIN joins LAB and COMPUTER on their common column, which is shown only once.

D3.30Practice4 marks

Write SQL queries for the following, based on the tables LAB and COMPUTER.

Table: LAB

LIDLNameIncharge
1Junior LabMs Roy
2Senior LabMr Das
3AI LabMs Paul

Table: COMPUTER

CompNoLIDBrandRAM
11Zenbook8
22Orbit16
32Zenbook8
43Lumo32
53Orbit16
  1. Show the Cartesian product of the two tables.
  2. Show the LName, Brand and RAM where the RAM is more than 8.
  3. Show each LName with the number of rows it has in COMPUTER.
  4. Show the rows of COMPUTER in descending order of RAM.
Answer
(i)
SELECT * FROM LAB, COMPUTER;

Output: 15 rows and 7 columns.

Explanation: With no join condition the result is the Cartesian product: 3 × 5 = 15 row pairs.

(ii)
SELECT LName, Brand, RAM FROM LAB, COMPUTER
  WHERE LAB.LID = COMPUTER.LID AND RAM > 8;
LNameBrandRAM
Senior LabOrbit16
AI LabLumo32
AI LabOrbit16

Explanation: The two tables LAB and COMPUTER are joined: only the row pairs where LAB.LID = COMPUTER.LID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: RAM is more than 8.

(iii)
SELECT LName, COUNT(*) FROM LAB, COMPUTER
  WHERE LAB.LID = COMPUTER.LID GROUP BY LName;
LNameCOUNT(*)
AI Lab2
Junior Lab1
Senior Lab2

Explanation: The two tables LAB and COMPUTER are joined: only the row pairs where LAB.LID = COMPUTER.LID are kept (an equi-join). The join gives 5 rows. GROUP BY LName makes 3 groups (AI Lab, Junior Lab, Senior Lab); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iv)
SELECT * FROM COMPUTER ORDER BY RAM DESC;
CompNoLIDBrandRAM
43Lumo32
22Orbit16
53Orbit16
11Zenbook8
32Zenbook8

Explanation: ORDER BY RAM arranges the result in descending (largest first) order.

D3.31Practice4 marks

Write SQL queries for the following, based on the tables LAB and COMPUTER.

Table: LAB

LIDLNameIncharge
1Junior LabMs Roy
2Senior LabMr Das
3AI LabMs Paul

Table: COMPUTER

CompNoLIDBrandRAM
11Zenbook8
22Orbit16
32Zenbook8
43Lumo32
53Orbit16
  1. Show the Brand and LName where the RAM is from 8 to 16.
  2. Show each LName with the highest RAM.
  3. Increase the RAM by 4 in the rows of COMPUTER whose LID is 1.
  4. Show the LName and Brand in ascending order of Brand.
Answer
(i)
SELECT Brand, LName FROM LAB, COMPUTER
  WHERE LAB.LID = COMPUTER.LID AND RAM BETWEEN 8 AND 16;
BrandLName
ZenbookJunior Lab
OrbitSenior Lab
ZenbookSenior Lab
OrbitAI Lab

Explanation: The two tables LAB and COMPUTER are joined: only the row pairs where LAB.LID = COMPUTER.LID are kept (an equi-join). Of the 5 joined rows, 4 match the other condition: RAM is from 8 to 16 (both included).

(ii)
SELECT LName, MAX(RAM) FROM LAB, COMPUTER
  WHERE LAB.LID = COMPUTER.LID GROUP BY LName;
LNameMAX(RAM)
AI Lab32
Junior Lab8
Senior Lab16

Explanation: The two tables LAB and COMPUTER are joined: only the row pairs where LAB.LID = COMPUTER.LID are kept (an equi-join). The join gives 5 rows. GROUP BY LName makes 3 groups (AI Lab, Junior Lab, Senior Lab); the aggregate function is worked out separately for each group. MAX gives the largest value.

(iii)
UPDATE COMPUTER SET RAM = RAM + 4 WHERE LID = 1;

1 row changed.

Explanation: SET RAM = RAM + 4 changes the value; WHERE limits the change to the rows where LID is 1: 1 row changed.

(iv)
SELECT LName, Brand FROM LAB, COMPUTER
  WHERE LAB.LID = COMPUTER.LID ORDER BY Brand;
LNameBrand
AI LabLumo
Senior LabOrbit
AI LabOrbit
Junior LabZenbook
Senior LabZenbook

Explanation: The two tables LAB and COMPUTER are joined: only the row pairs where LAB.LID = COMPUTER.LID are kept (an equi-join). The join gives 5 rows. ORDER BY Brand arranges the result in ascending (smallest first) order.

D3.32Practice4 marks

Write SQL queries for the following, based on the tables CINEMA and SCREENING.

Table: CINEMA

CIDCNameCity
1GalaxyIndore
2RegalBhopal
3OrionIndore

Table: SCREENING

ShowNoCIDFilmPrice
11Udaan180
22Safar150
33Udaan220
41Nadi200
52Sapna160
  1. Show each Film with its CName.
  2. Show the Film of the rows whose City is 'Indore'.
  3. Show each CName with the total Price.
  4. Show all the columns of both tables using a natural join.
Answer
(i)
SELECT Film, CName FROM CINEMA, SCREENING
  WHERE CINEMA.CID = SCREENING.CID;
FilmCName
NadiGalaxy
UdaanGalaxy
SafarRegal
SapnaRegal
UdaanOrion

Explanation: The two tables CINEMA and SCREENING are joined: only the row pairs where CINEMA.CID = SCREENING.CID are kept (an equi-join). The join gives 5 rows.

(ii)
SELECT Film FROM CINEMA, SCREENING
  WHERE CINEMA.CID = SCREENING.CID AND City = 'Indore';
Film
Nadi
Udaan
Udaan

Explanation: The two tables CINEMA and SCREENING are joined: only the row pairs where CINEMA.CID = SCREENING.CID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: City is 'Indore'.

(iii)
SELECT CName, SUM(Price) FROM CINEMA, SCREENING
  WHERE CINEMA.CID = SCREENING.CID GROUP BY CName;
CNameSUM(Price)
Galaxy380
Orion220
Regal310

Explanation: The two tables CINEMA and SCREENING are joined: only the row pairs where CINEMA.CID = SCREENING.CID are kept (an equi-join). The join gives 5 rows. GROUP BY CName makes 3 groups (Galaxy, Orion, Regal); the aggregate function is worked out separately for each group. SUM adds the values.

(iv)
SELECT * FROM CINEMA NATURAL JOIN SCREENING;
CIDCNameCityShowNoFilmPrice
1GalaxyIndore1Udaan180
1GalaxyIndore4Nadi200
2RegalBhopal2Safar150
2RegalBhopal5Sapna160
3OrionIndore3Udaan220

Explanation: NATURAL JOIN joins CINEMA and SCREENING on their common column, which is shown only once.

D3.33Practice4 marks

Write SQL queries for the following, based on the tables CINEMA and SCREENING.

Table: CINEMA

CIDCNameCity
1GalaxyIndore
2RegalBhopal
3OrionIndore

Table: SCREENING

ShowNoCIDFilmPrice
11Udaan180
22Safar150
33Udaan220
41Nadi200
52Sapna160
  1. Show the Cartesian product of the two tables.
  2. Show the CName, Film and Price where the Price is more than 170.
  3. Show each CName with the number of rows it has in SCREENING.
  4. Show the rows of SCREENING in descending order of Price.
Answer
(i)
SELECT * FROM CINEMA, SCREENING;

Output: 15 rows and 7 columns.

Explanation: With no join condition the result is the Cartesian product: 3 × 5 = 15 row pairs.

(ii)
SELECT CName, Film, Price FROM CINEMA, SCREENING
  WHERE CINEMA.CID = SCREENING.CID AND Price > 170;
CNameFilmPrice
GalaxyUdaan180
OrionUdaan220
GalaxyNadi200

Explanation: The two tables CINEMA and SCREENING are joined: only the row pairs where CINEMA.CID = SCREENING.CID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Price is more than 170.

(iii)
SELECT CName, COUNT(*) FROM CINEMA, SCREENING
  WHERE CINEMA.CID = SCREENING.CID GROUP BY CName;
CNameCOUNT(*)
Galaxy2
Orion1
Regal2

Explanation: The two tables CINEMA and SCREENING are joined: only the row pairs where CINEMA.CID = SCREENING.CID are kept (an equi-join). The join gives 5 rows. GROUP BY CName makes 3 groups (Galaxy, Orion, Regal); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iv)
SELECT * FROM SCREENING ORDER BY Price DESC;
ShowNoCIDFilmPrice
33Udaan220
41Nadi200
11Udaan180
52Sapna160
22Safar150

Explanation: ORDER BY Price arranges the result in descending (largest first) order.

D3.34Practice4 marks

Write SQL queries for the following, based on the tables CINEMA and SCREENING.

Table: CINEMA

CIDCNameCity
1GalaxyIndore
2RegalBhopal
3OrionIndore

Table: SCREENING

ShowNoCIDFilmPrice
11Udaan180
22Safar150
33Udaan220
41Nadi200
52Sapna160
  1. Show the Film and CName where the Price is from 150 to 200.
  2. Show each CName with the highest Price.
  3. Increase the Price by 20 in the rows of SCREENING whose CID is 2.
  4. Show the CName and Film in ascending order of Film.
Answer
(i)
SELECT Film, CName FROM CINEMA, SCREENING
  WHERE CINEMA.CID = SCREENING.CID AND Price BETWEEN 150 AND 200;
FilmCName
UdaanGalaxy
SafarRegal
NadiGalaxy
SapnaRegal

Explanation: The two tables CINEMA and SCREENING are joined: only the row pairs where CINEMA.CID = SCREENING.CID are kept (an equi-join). Of the 5 joined rows, 4 match the other condition: Price is from 150 to 200 (both included).

(ii)
SELECT CName, MAX(Price) FROM CINEMA, SCREENING
  WHERE CINEMA.CID = SCREENING.CID GROUP BY CName;
CNameMAX(Price)
Galaxy200
Orion220
Regal160

Explanation: The two tables CINEMA and SCREENING are joined: only the row pairs where CINEMA.CID = SCREENING.CID are kept (an equi-join). The join gives 5 rows. GROUP BY CName makes 3 groups (Galaxy, Orion, Regal); the aggregate function is worked out separately for each group. MAX gives the largest value.

(iii)
UPDATE SCREENING SET Price = Price + 20 WHERE CID = 2;

2 rows changed.

Explanation: SET Price = Price + 20 changes the value; WHERE limits the change to the rows where CID is 2: 2 rows changed.

(iv)
SELECT CName, Film FROM CINEMA, SCREENING
  WHERE CINEMA.CID = SCREENING.CID ORDER BY Film;
CNameFilm
GalaxyNadi
RegalSafar
RegalSapna
GalaxyUdaan
OrionUdaan

Explanation: The two tables CINEMA and SCREENING are joined: only the row pairs where CINEMA.CID = SCREENING.CID are kept (an equi-join). The join gives 5 rows. ORDER BY Film arranges the result in ascending (smallest first) order.

D3.35Practice4 marks

Write SQL queries for the following, based on the tables FARM and CROP.

Table: FARM

FIDOwnerVillage
1BalbirRampur
2SavitriSonpur
3GurmeetRampur

Table: CROP

CropNoFIDCropNameYield
11Wheat42
22Rice35
31Mustard18
43Wheat50
52Maize27
  1. Show each CropName with its Owner.
  2. Show the CropName of the rows whose Village is 'Rampur'.
  3. Show each Owner with the total Yield.
  4. Show all the columns of both tables using a natural join.
Answer
(i)
SELECT CropName, Owner FROM FARM, CROP
  WHERE FARM.FID = CROP.FID;
CropNameOwner
MustardBalbir
WheatBalbir
MaizeSavitri
RiceSavitri
WheatGurmeet

Explanation: The two tables FARM and CROP are joined: only the row pairs where FARM.FID = CROP.FID are kept (an equi-join). The join gives 5 rows.

(ii)
SELECT CropName FROM FARM, CROP
  WHERE FARM.FID = CROP.FID AND Village = 'Rampur';
CropName
Mustard
Wheat
Wheat

Explanation: The two tables FARM and CROP are joined: only the row pairs where FARM.FID = CROP.FID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Village is 'Rampur'.

(iii)
SELECT Owner, SUM(Yield) FROM FARM, CROP
  WHERE FARM.FID = CROP.FID GROUP BY Owner;
OwnerSUM(Yield)
Balbir60
Gurmeet50
Savitri62

Explanation: The two tables FARM and CROP are joined: only the row pairs where FARM.FID = CROP.FID are kept (an equi-join). The join gives 5 rows. GROUP BY Owner makes 3 groups (Balbir, Gurmeet, Savitri); the aggregate function is worked out separately for each group. SUM adds the values.

(iv)
SELECT * FROM FARM NATURAL JOIN CROP;
FIDOwnerVillageCropNoCropNameYield
1BalbirRampur1Wheat42
1BalbirRampur3Mustard18
2SavitriSonpur2Rice35
2SavitriSonpur5Maize27
3GurmeetRampur4Wheat50

Explanation: NATURAL JOIN joins FARM and CROP on their common column, which is shown only once.

D3.36Practice4 marks

Write SQL queries for the following, based on the tables FARM and CROP.

Table: FARM

FIDOwnerVillage
1BalbirRampur
2SavitriSonpur
3GurmeetRampur

Table: CROP

CropNoFIDCropNameYield
11Wheat42
22Rice35
31Mustard18
43Wheat50
52Maize27
  1. Show the Cartesian product of the two tables.
  2. Show the Owner, CropName and Yield where the Yield is more than 30.
  3. Show each Owner with the number of rows it has in CROP.
  4. Show the rows of CROP in descending order of Yield.
Answer
(i)
SELECT * FROM FARM, CROP;

Output: 15 rows and 7 columns.

Explanation: With no join condition the result is the Cartesian product: 3 × 5 = 15 row pairs.

(ii)
SELECT Owner, CropName, Yield FROM FARM, CROP
  WHERE FARM.FID = CROP.FID AND Yield > 30;
OwnerCropNameYield
BalbirWheat42
SavitriRice35
GurmeetWheat50

Explanation: The two tables FARM and CROP are joined: only the row pairs where FARM.FID = CROP.FID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Yield is more than 30.

(iii)
SELECT Owner, COUNT(*) FROM FARM, CROP
  WHERE FARM.FID = CROP.FID GROUP BY Owner;
OwnerCOUNT(*)
Balbir2
Gurmeet1
Savitri2

Explanation: The two tables FARM and CROP are joined: only the row pairs where FARM.FID = CROP.FID are kept (an equi-join). The join gives 5 rows. GROUP BY Owner makes 3 groups (Balbir, Gurmeet, Savitri); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iv)
SELECT * FROM CROP ORDER BY Yield DESC;
CropNoFIDCropNameYield
43Wheat50
11Wheat42
22Rice35
52Maize27
31Mustard18

Explanation: ORDER BY Yield arranges the result in descending (largest first) order.

D3.37Practice4 marks

Write SQL queries for the following, based on the tables FARM and CROP.

Table: FARM

FIDOwnerVillage
1BalbirRampur
2SavitriSonpur
3GurmeetRampur

Table: CROP

CropNoFIDCropNameYield
11Wheat42
22Rice35
31Mustard18
43Wheat50
52Maize27
  1. Show the CropName and Owner where the Yield is from 25 to 45.
  2. Show each Owner with the highest Yield.
  3. Increase the Yield by 5 in the rows of CROP whose FID is 3.
  4. Show the Owner and CropName in ascending order of CropName.
Answer
(i)
SELECT CropName, Owner FROM FARM, CROP
  WHERE FARM.FID = CROP.FID AND Yield BETWEEN 25 AND 45;
CropNameOwner
WheatBalbir
RiceSavitri
MaizeSavitri

Explanation: The two tables FARM and CROP are joined: only the row pairs where FARM.FID = CROP.FID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Yield is from 25 to 45 (both included).

(ii)
SELECT Owner, MAX(Yield) FROM FARM, CROP
  WHERE FARM.FID = CROP.FID GROUP BY Owner;
OwnerMAX(Yield)
Balbir42
Gurmeet50
Savitri35

Explanation: The two tables FARM and CROP are joined: only the row pairs where FARM.FID = CROP.FID are kept (an equi-join). The join gives 5 rows. GROUP BY Owner makes 3 groups (Balbir, Gurmeet, Savitri); the aggregate function is worked out separately for each group. MAX gives the largest value.

(iii)
UPDATE CROP SET Yield = Yield + 5 WHERE FID = 3;

1 row changed.

Explanation: SET Yield = Yield + 5 changes the value; WHERE limits the change to the rows where FID is 3: 1 row changed.

(iv)
SELECT Owner, CropName FROM FARM, CROP
  WHERE FARM.FID = CROP.FID ORDER BY CropName;
OwnerCropName
SavitriMaize
BalbirMustard
SavitriRice
BalbirWheat
GurmeetWheat

Explanation: The two tables FARM and CROP are joined: only the row pairs where FARM.FID = CROP.FID are kept (an equi-join). The join gives 5 rows. ORDER BY CropName arranges the result in ascending (smallest first) order.

D3.38Practice4 marks

Write SQL queries for the following, based on the tables COACH and TRAINEE.

Table: COACH

CIDCNameGame
1Mr GillHockey
2Ms NairBadminton
3Mr BoseFootball

Table: TRAINEE

TIDTNameCIDScore
1Uday164
2Veena288
3Wasim371
4Yash179
5Zoya293
  1. Show each TName with its CName.
  2. Show the TName of the rows whose Game is 'Badminton'.
  3. Show each CName with the total Score.
  4. Show all the columns of both tables using a natural join.
Answer
(i)
SELECT TName, CName FROM COACH, TRAINEE
  WHERE COACH.CID = TRAINEE.CID;
TNameCName
UdayMr Gill
YashMr Gill
VeenaMs Nair
ZoyaMs Nair
WasimMr Bose

Explanation: The two tables COACH and TRAINEE are joined: only the row pairs where COACH.CID = TRAINEE.CID are kept (an equi-join). The join gives 5 rows.

(ii)
SELECT TName FROM COACH, TRAINEE
  WHERE COACH.CID = TRAINEE.CID AND Game = 'Badminton';
TName
Veena
Zoya

Explanation: The two tables COACH and TRAINEE are joined: only the row pairs where COACH.CID = TRAINEE.CID are kept (an equi-join). Of the 5 joined rows, 2 match the other condition: Game is 'Badminton'.

(iii)
SELECT CName, SUM(Score) FROM COACH, TRAINEE
  WHERE COACH.CID = TRAINEE.CID GROUP BY CName;
CNameSUM(Score)
Mr Bose71
Mr Gill143
Ms Nair181

Explanation: The two tables COACH and TRAINEE are joined: only the row pairs where COACH.CID = TRAINEE.CID are kept (an equi-join). The join gives 5 rows. GROUP BY CName makes 3 groups (Mr Bose, Mr Gill, Ms Nair); the aggregate function is worked out separately for each group. SUM adds the values.

(iv)
SELECT * FROM COACH NATURAL JOIN TRAINEE;
CIDCNameGameTIDTNameScore
1Mr GillHockey1Uday64
1Mr GillHockey4Yash79
2Ms NairBadminton2Veena88
2Ms NairBadminton5Zoya93
3Mr BoseFootball3Wasim71

Explanation: NATURAL JOIN joins COACH and TRAINEE on their common column, which is shown only once.

D3.39Practice4 marks

Write SQL queries for the following, based on the tables COACH and TRAINEE.

Table: COACH

CIDCNameGame
1Mr GillHockey
2Ms NairBadminton
3Mr BoseFootball

Table: TRAINEE

TIDTNameCIDScore
1Uday164
2Veena288
3Wasim371
4Yash179
5Zoya293
  1. Show the Cartesian product of the two tables.
  2. Show the CName, TName and Score where the Score is more than 75.
  3. Show each CName with the number of rows it has in TRAINEE.
  4. Show the rows of TRAINEE in descending order of Score.
Answer
(i)
SELECT * FROM COACH, TRAINEE;

Output: 15 rows and 7 columns.

Explanation: With no join condition the result is the Cartesian product: 3 × 5 = 15 row pairs.

(ii)
SELECT CName, TName, Score FROM COACH, TRAINEE
  WHERE COACH.CID = TRAINEE.CID AND Score > 75;
CNameTNameScore
Ms NairVeena88
Mr GillYash79
Ms NairZoya93

Explanation: The two tables COACH and TRAINEE are joined: only the row pairs where COACH.CID = TRAINEE.CID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Score is more than 75.

(iii)
SELECT CName, COUNT(*) FROM COACH, TRAINEE
  WHERE COACH.CID = TRAINEE.CID GROUP BY CName;
CNameCOUNT(*)
Mr Bose1
Mr Gill2
Ms Nair2

Explanation: The two tables COACH and TRAINEE are joined: only the row pairs where COACH.CID = TRAINEE.CID are kept (an equi-join). The join gives 5 rows. GROUP BY CName makes 3 groups (Mr Bose, Mr Gill, Ms Nair); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.

(iv)
SELECT * FROM TRAINEE ORDER BY Score DESC;
TIDTNameCIDScore
5Zoya293
2Veena288
4Yash179
3Wasim371
1Uday164

Explanation: ORDER BY Score arranges the result in descending (largest first) order.

D3.40Practice4 marks

Write SQL queries for the following, based on the tables COACH and TRAINEE.

Table: COACH

CIDCNameGame
1Mr GillHockey
2Ms NairBadminton
3Mr BoseFootball

Table: TRAINEE

TIDTNameCIDScore
1Uday164
2Veena288
3Wasim371
4Yash179
5Zoya293
  1. Show the TName and CName where the Score is from 70 to 90.
  2. Show each CName with the highest Score.
  3. Increase the Score by 3 in the rows of TRAINEE whose CID is 3.
  4. Show the CName and TName in ascending order of TName.
Answer
(i)
SELECT TName, CName FROM COACH, TRAINEE
  WHERE COACH.CID = TRAINEE.CID AND Score BETWEEN 70 AND 90;
TNameCName
VeenaMs Nair
WasimMr Bose
YashMr Gill

Explanation: The two tables COACH and TRAINEE are joined: only the row pairs where COACH.CID = TRAINEE.CID are kept (an equi-join). Of the 5 joined rows, 3 match the other condition: Score is from 70 to 90 (both included).

(ii)
SELECT CName, MAX(Score) FROM COACH, TRAINEE
  WHERE COACH.CID = TRAINEE.CID GROUP BY CName;
CNameMAX(Score)
Mr Bose71
Mr Gill79
Ms Nair93

Explanation: The two tables COACH and TRAINEE are joined: only the row pairs where COACH.CID = TRAINEE.CID are kept (an equi-join). The join gives 5 rows. GROUP BY CName makes 3 groups (Mr Bose, Mr Gill, Ms Nair); the aggregate function is worked out separately for each group. MAX gives the largest value.

(iii)
UPDATE TRAINEE SET Score = Score + 3 WHERE CID = 3;

1 row changed.

Explanation: SET Score = Score + 3 changes the value; WHERE limits the change to the rows where CID is 3: 1 row changed.

(iv)
SELECT CName, TName FROM COACH, TRAINEE
  WHERE COACH.CID = TRAINEE.CID ORDER BY TName;
CNameTName
Mr GillUday
Ms NairVeena
Mr BoseWasim
Mr GillYash
Ms NairZoya

Explanation: The two tables COACH and TRAINEE are joined: only the row pairs where COACH.CID = TRAINEE.CID are kept (an equi-join). The join gives 5 rows. ORDER BY TName arranges the result in ascending (smallest first) order.

D4Python-MySQL connectivity4 marks · 40 questions
D4.1SQP 2026-274 marks

Database LibraryDB has the table book_records (Book_ID, Book_Title, Author, Copies). Write a program that changes Book_Title to 'Data Structures in Python' for Book_ID 109. User: librarian, password: lib@2025, host: localhost.

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="librarian",
        password="lib@2025", database="LibraryDB")
cur = con.cursor()
cur.execute("UPDATE book_records SET Book_Title = 'Data Structures in Python' WHERE Book_ID = 109")
con.commit()
con.close()
D4.2CBSE 20264 marks

Write a program to display all the records of the table Account in the database SCHOOL where Fees is less than 5000.

Answer

Use the user name and password given in the question paper.

import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SCHOOL")
cur = con.cursor()
cur.execute("SELECT * FROM Account WHERE Fees < 5000")
for rec in cur.fetchall():
    print(rec)
con.close()
D4.3CBSE 20254 marks

Write a function Delete_Theatre() that inputs a theatre ID and deletes that record from the table THEATRE of the database CINEMA. User: root, password: Ex2025.

Answer
import mysql.connector
def Delete_Theatre():
    con = mysql.connector.connect(host="localhost", user="root",
            password="Ex2025", database="CINEMA")
    cur = con.cursor()
    tid = input("Enter Theatre ID: ")
    cur.execute("DELETE FROM THEATRE WHERE Th_ID = %s", (tid,))
    con.commit()
    con.close()
D4.4Practice4 marks

Table STUDENT (RNo, Name, Marks) is in the database SCHOOL. Write a function AddStudent() that inputs one record and inserts it into the table.

Answer
import mysql.connector
def AddStudent():
    con = mysql.connector.connect(host="localhost", user="root",
            password="tiger", database="SCHOOL")
    cur = con.cursor()
    r = int(input("Roll no: "))
    n = input("Name: ")
    m = int(input("Marks: "))
    cur.execute("INSERT INTO STUDENT VALUES (%s, %s, %s)", (r, n, m))
    con.commit()
    con.close()
D4.5Practice4 marks

Write a program to display all the records of the table ITEM in the database SHOP, one record on each line, and then the total number of records.

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SHOP")
cur = con.cursor()
cur.execute("SELECT * FROM ITEM")
data = cur.fetchall()
for rec in data:
    print(rec)
print("Total records:", cur.rowcount)
con.close()
D4.6Practice4 marks

Table EMP (ENo, EName, Salary) is in the database OFFICE. Write a program that inputs an employee number and an amount, and increases that employee's salary by the amount.

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="OFFICE")
cur = con.cursor()
eno = int(input("Employee no: "))
amt = int(input("Increase by: "))
cur.execute("UPDATE EMP SET Salary = Salary + %s WHERE ENo = %s", (amt, eno))
con.commit()
print(cur.rowcount, "record updated")
con.close()
D4.7Practice4 marks

Table BOOK (BNo, Title, Price) is in the database LIBRARY. Write a program that inputs a book number and displays its record, or "Book not found".

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="LIBRARY")
cur = con.cursor()
bno = int(input("Book no: "))
cur.execute("SELECT * FROM BOOK WHERE BNo = %s", (bno,))
rec = cur.fetchone()
if rec is None:
    print("Book not found")
else:
    print(rec)
con.close()
D4.8Practice4 marks

Table PLAYER (PID, PName, Runs) is in the database SPORTS. Write a program to display the names of the players who scored more than 500 runs.

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SPORTS")
cur = con.cursor()
cur.execute("SELECT PName FROM PLAYER WHERE Runs > 500")
for rec in cur.fetchall():
    print(rec[0])
con.close()
D4.9Practice4 marks

Table MEMBER (MNo, MName, City) is in the database CLUB. Write a program that inputs a city and deletes all the members of that city.

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="CLUB")
cur = con.cursor()
city = input("City: ")
cur.execute("DELETE FROM MEMBER WHERE City = %s", (city,))
con.commit()
print(cur.rowcount, "records deleted")
con.close()
D4.10Practice4 marks

Write a program that creates the table RESULT (RNo integer primary key, Name varchar(20), Percent float) in the database SCHOOL and inserts the row (1, 'Asha', 91.5).

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SCHOOL")
cur = con.cursor()
cur.execute("CREATE TABLE RESULT (RNo INT PRIMARY KEY, Name VARCHAR(20), Percent FLOAT)")
cur.execute("INSERT INTO RESULT VALUES (1, 'Asha', 91.5)")
con.commit()
con.close()
D4.11Practice4 marks

The table TEACHER (TNo, TName, Subject, Salary, City) is in the database SCHOOL. Write a program that inputs the details of one teacher and inserts the record into the table. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SCHOOL")
cur = con.cursor()
tno = int(input("TNo: "))
tname = input("TName: ")
subject = input("Subject: ")
salary = int(input("Salary: "))
city = input("City: ")
cur.execute("INSERT INTO TEACHER VALUES (%s, %s, %s, %s, %s)", (tno, tname, subject, salary, city))
con.commit()
con.close()
D4.12Practice4 marks

The table TEACHER (TNo, TName, Subject, Salary, City) is in the database SCHOOL. Write a program that inputs a value and displays the teachers whose Salary is more than that value. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SCHOOL")
cur = con.cursor()
v = int(input("Enter Salary: "))
cur.execute("SELECT * FROM TEACHER WHERE Salary > %s", (v,))
for rec in cur.fetchall():
    print(rec)
con.close()
D4.13Practice4 marks

The table TEACHER (TNo, TName, Subject, Salary, City) is in the database SCHOOL. Write a program that inputs a TNo and a new Salary, changes the Salary of that teacher, and displays how many records were changed. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SCHOOL")
cur = con.cursor()
k = int(input("Enter TNo: "))
n = int(input("New Salary: "))
cur.execute("UPDATE TEACHER SET Salary = %s WHERE TNo = %s", (n, k))
con.commit()
print(cur.rowcount, "record(s) changed")
con.close()
D4.14Practice4 marks

The table MOVIE (MNo, Title, Language, Rating, Tickets) is in the database CINEMA. Write a program that inputs the details of one movie and inserts the record into the table. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="CINEMA")
cur = con.cursor()
mno = int(input("MNo: "))
title = input("Title: ")
language = input("Language: ")
rating = int(input("Rating: "))
tickets = int(input("Tickets: "))
cur.execute("INSERT INTO MOVIE VALUES (%s, %s, %s, %s, %s)", (mno, title, language, rating, tickets))
con.commit()
con.close()
D4.15Practice4 marks

The table MOVIE (MNo, Title, Language, Rating, Tickets) is in the database CINEMA. Write a program that inputs a value and displays the movies whose Tickets is more than that value. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="CINEMA")
cur = con.cursor()
v = int(input("Enter Tickets: "))
cur.execute("SELECT * FROM MOVIE WHERE Tickets > %s", (v,))
for rec in cur.fetchall():
    print(rec)
con.close()
D4.16Practice4 marks

The table MOVIE (MNo, Title, Language, Rating, Tickets) is in the database CINEMA. Write a program that inputs a MNo and a new Tickets, changes the Tickets of that movie, and displays how many records were changed. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="CINEMA")
cur = con.cursor()
k = int(input("Enter MNo: "))
n = int(input("New Tickets: "))
cur.execute("UPDATE MOVIE SET Tickets = %s WHERE MNo = %s", (n, k))
con.commit()
print(cur.rowcount, "record(s) changed")
con.close()
D4.17Practice4 marks

The table FLIGHT (FNo, Airline, Source, Seats, Fare) is in the database AIRLINE. Write a program that inputs the details of one flight and inserts the record into the table. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="AIRLINE")
cur = con.cursor()
fno = input("FNo: ")
airline = input("Airline: ")
source = input("Source: ")
seats = int(input("Seats: "))
fare = int(input("Fare: "))
cur.execute("INSERT INTO FLIGHT VALUES (%s, %s, %s, %s, %s)", (fno, airline, source, seats, fare))
con.commit()
con.close()
D4.18Practice4 marks

The table FLIGHT (FNo, Airline, Source, Seats, Fare) is in the database AIRLINE. Write a program that inputs a value and displays the flights whose Fare is more than that value. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="AIRLINE")
cur = con.cursor()
v = int(input("Enter Fare: "))
cur.execute("SELECT * FROM FLIGHT WHERE Fare > %s", (v,))
for rec in cur.fetchall():
    print(rec)
con.close()
D4.19Practice4 marks

The table FLIGHT (FNo, Airline, Source, Seats, Fare) is in the database AIRLINE. Write a program that inputs a FNo and a new Fare, changes the Fare of that flight, and displays how many records were changed. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="AIRLINE")
cur = con.cursor()
k = input("Enter FNo: ")
n = int(input("New Fare: "))
cur.execute("UPDATE FLIGHT SET Fare = %s WHERE FNo = %s", (n, k))
con.commit()
print(cur.rowcount, "record(s) changed")
con.close()
D4.20Practice4 marks

The table MOBILE (MID, Model, Brand, Price, Stock) is in the database STORE. Write a program that inputs the details of one mobile and inserts the record into the table. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="STORE")
cur = con.cursor()
mid = int(input("MID: "))
model = input("Model: ")
brand = input("Brand: ")
price = int(input("Price: "))
stock = int(input("Stock: "))
cur.execute("INSERT INTO MOBILE VALUES (%s, %s, %s, %s, %s)", (mid, model, brand, price, stock))
con.commit()
con.close()
D4.21Practice4 marks

The table MOBILE (MID, Model, Brand, Price, Stock) is in the database STORE. Write a program that inputs a value and displays the mobiles whose Price is more than that value. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="STORE")
cur = con.cursor()
v = int(input("Enter Price: "))
cur.execute("SELECT * FROM MOBILE WHERE Price > %s", (v,))
for rec in cur.fetchall():
    print(rec)
con.close()
D4.22Practice4 marks

The table MOBILE (MID, Model, Brand, Price, Stock) is in the database STORE. Write a program that inputs a MID and a new Price, changes the Price of that mobile, and displays how many records were changed. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="STORE")
cur = con.cursor()
k = int(input("Enter MID: "))
n = int(input("New Price: "))
cur.execute("UPDATE MOBILE SET Price = %s WHERE MID = %s", (n, k))
con.commit()
print(cur.rowcount, "record(s) changed")
con.close()
D4.23Practice4 marks

The table PATIENT (PID, PName, Ward, Days, Bill) is in the database HOSPITAL. Write a program that inputs the details of one patient and inserts the record into the table. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="HOSPITAL")
cur = con.cursor()
pid = int(input("PID: "))
pname = input("PName: ")
ward = input("Ward: ")
days = int(input("Days: "))
bill = int(input("Bill: "))
cur.execute("INSERT INTO PATIENT VALUES (%s, %s, %s, %s, %s)", (pid, pname, ward, days, bill))
con.commit()
con.close()
D4.24Practice4 marks

The table PATIENT (PID, PName, Ward, Days, Bill) is in the database HOSPITAL. Write a program that inputs a value and displays the patients whose Bill is more than that value. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="HOSPITAL")
cur = con.cursor()
v = int(input("Enter Bill: "))
cur.execute("SELECT * FROM PATIENT WHERE Bill > %s", (v,))
for rec in cur.fetchall():
    print(rec)
con.close()
D4.25Practice4 marks

The table PATIENT (PID, PName, Ward, Days, Bill) is in the database HOSPITAL. Write a program that inputs a PID and a new Bill, changes the Bill of that patient, and displays how many records were changed. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="HOSPITAL")
cur = con.cursor()
k = int(input("Enter PID: "))
n = int(input("New Bill: "))
cur.execute("UPDATE PATIENT SET Bill = %s WHERE PID = %s", (n, k))
con.commit()
print(cur.rowcount, "record(s) changed")
con.close()
D4.26Practice4 marks

The table CLUB (MemNo, MName, Sport, Fee, Age) is in the database SPORTS. Write a program that inputs the details of one member and inserts the record into the table. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SPORTS")
cur = con.cursor()
memno = int(input("MemNo: "))
mname = input("MName: ")
sport = input("Sport: ")
fee = int(input("Fee: "))
age = int(input("Age: "))
cur.execute("INSERT INTO CLUB VALUES (%s, %s, %s, %s, %s)", (memno, mname, sport, fee, age))
con.commit()
con.close()
D4.27Practice4 marks

The table CLUB (MemNo, MName, Sport, Fee, Age) is in the database SPORTS. Write a program that inputs a value and displays the members whose Fee is more than that value. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SPORTS")
cur = con.cursor()
v = int(input("Enter Fee: "))
cur.execute("SELECT * FROM CLUB WHERE Fee > %s", (v,))
for rec in cur.fetchall():
    print(rec)
con.close()
D4.28Practice4 marks

The table CLUB (MemNo, MName, Sport, Fee, Age) is in the database SPORTS. Write a program that inputs a MemNo and a new Fee, changes the Fee of that member, and displays how many records were changed. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SPORTS")
cur = con.cursor()
k = int(input("Enter MemNo: "))
n = int(input("New Fee: "))
cur.execute("UPDATE CLUB SET Fee = %s WHERE MemNo = %s", (n, k))
con.commit()
print(cur.rowcount, "record(s) changed")
con.close()
D4.29Practice4 marks

The table GARMENT (GCode, GName, Size, Price, Qty) is in the database SHOP. Write a program that inputs the details of one garment and inserts the record into the table. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SHOP")
cur = con.cursor()
gcode = input("GCode: ")
gname = input("GName: ")
size = input("Size: ")
price = int(input("Price: "))
qty = int(input("Qty: "))
cur.execute("INSERT INTO GARMENT VALUES (%s, %s, %s, %s, %s)", (gcode, gname, size, price, qty))
con.commit()
con.close()
D4.30Practice4 marks

The table GARMENT (GCode, GName, Size, Price, Qty) is in the database SHOP. Write a program that inputs a value and displays the garments whose Price is more than that value. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SHOP")
cur = con.cursor()
v = int(input("Enter Price: "))
cur.execute("SELECT * FROM GARMENT WHERE Price > %s", (v,))
for rec in cur.fetchall():
    print(rec)
con.close()
D4.31Practice4 marks

The table GARMENT (GCode, GName, Size, Price, Qty) is in the database SHOP. Write a program that inputs a GCode and a new Price, changes the Price of that garment, and displays how many records were changed. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="SHOP")
cur = con.cursor()
k = input("Enter GCode: ")
n = int(input("New Price: "))
cur.execute("UPDATE GARMENT SET Price = %s WHERE GCode = %s", (n, k))
con.commit()
print(cur.rowcount, "record(s) changed")
con.close()
D4.32Practice4 marks

The table COURSE (CID, CName, Mode, Fees, Seats) is in the database ACADEMY. Write a program that inputs the details of one course and inserts the record into the table. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="ACADEMY")
cur = con.cursor()
cid = input("CID: ")
cname = input("CName: ")
mode = input("Mode: ")
fees = int(input("Fees: "))
seats = int(input("Seats: "))
cur.execute("INSERT INTO COURSE VALUES (%s, %s, %s, %s, %s)", (cid, cname, mode, fees, seats))
con.commit()
con.close()
D4.33Practice4 marks

The table COURSE (CID, CName, Mode, Fees, Seats) is in the database ACADEMY. Write a program that inputs a value and displays the courses whose Fees is more than that value. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="ACADEMY")
cur = con.cursor()
v = int(input("Enter Fees: "))
cur.execute("SELECT * FROM COURSE WHERE Fees > %s", (v,))
for rec in cur.fetchall():
    print(rec)
con.close()
D4.34Practice4 marks

The table COURSE (CID, CName, Mode, Fees, Seats) is in the database ACADEMY. Write a program that inputs a CID and a new Fees, changes the Fees of that course, and displays how many records were changed. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="ACADEMY")
cur = con.cursor()
k = input("Enter CID: ")
n = int(input("New Fees: "))
cur.execute("UPDATE COURSE SET Fees = %s WHERE CID = %s", (n, k))
con.commit()
print(cur.rowcount, "record(s) changed")
con.close()
D4.35Practice4 marks

The table HOSTEL (RoomNo, SName, Block, Rent, Sem) is in the database CAMPUS. Write a program that inputs the details of one student and inserts the record into the table. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="CAMPUS")
cur = con.cursor()
roomno = int(input("RoomNo: "))
sname = input("SName: ")
block = input("Block: ")
rent = int(input("Rent: "))
sem = int(input("Sem: "))
cur.execute("INSERT INTO HOSTEL VALUES (%s, %s, %s, %s, %s)", (roomno, sname, block, rent, sem))
con.commit()
con.close()
D4.36Practice4 marks

The table HOSTEL (RoomNo, SName, Block, Rent, Sem) is in the database CAMPUS. Write a program that inputs a value and displays the students whose Rent is more than that value. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="CAMPUS")
cur = con.cursor()
v = int(input("Enter Rent: "))
cur.execute("SELECT * FROM HOSTEL WHERE Rent > %s", (v,))
for rec in cur.fetchall():
    print(rec)
con.close()
D4.37Practice4 marks

The table HOSTEL (RoomNo, SName, Block, Rent, Sem) is in the database CAMPUS. Write a program that inputs a RoomNo and a new Rent, changes the Rent of that student, and displays how many records were changed. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="CAMPUS")
cur = con.cursor()
k = int(input("Enter RoomNo: "))
n = int(input("New Rent: "))
cur.execute("UPDATE HOSTEL SET Rent = %s WHERE RoomNo = %s", (n, k))
con.commit()
print(cur.rowcount, "record(s) changed")
con.close()
D4.38Practice4 marks

The table BUS (BusNo, Route, Depot, Seats, Fare) is in the database TRANSPORT. Write a program that inputs the details of one bus and inserts the record into the table. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="TRANSPORT")
cur = con.cursor()
busno = input("BusNo: ")
route = input("Route: ")
depot = input("Depot: ")
seats = int(input("Seats: "))
fare = int(input("Fare: "))
cur.execute("INSERT INTO BUS VALUES (%s, %s, %s, %s, %s)", (busno, route, depot, seats, fare))
con.commit()
con.close()
D4.39Practice4 marks

The table BUS (BusNo, Route, Depot, Seats, Fare) is in the database TRANSPORT. Write a program that inputs a value and displays the buses whose Fare is more than that value. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="TRANSPORT")
cur = con.cursor()
v = int(input("Enter Fare: "))
cur.execute("SELECT * FROM BUS WHERE Fare > %s", (v,))
for rec in cur.fetchall():
    print(rec)
con.close()
D4.40Practice4 marks

The table BUS (BusNo, Route, Depot, Seats, Fare) is in the database TRANSPORT. Write a program that inputs a BusNo and a new Fare, changes the Fare of that bus, and displays how many records were changed. (User: root, password: tiger, host: localhost.)

Answer
import mysql.connector
con = mysql.connector.connect(host="localhost", user="root",
        password="tiger", database="TRANSPORT")
cur = con.cursor()
k = input("Enter BusNo: ")
n = int(input("New Fare: "))
cur.execute("UPDATE BUS SET Fare = %s WHERE BusNo = %s", (n, k))
con.commit()
print(cur.rowcount, "record(s) changed")
con.close()

Section E · 5 marks each

E1Binary file functions5 marks · 40 questions
E1.1SQP 2026-275 marks

A college keeps enrolment records with Roll_No, Student_Name, Course and Fees in a binary file. Write:

  1. A function to input one record and append it to the file
  2. A function to change the Fees to 75000 for all students of the course "Data Science". (The file name Enrollments.dat is assumed here.)
Answer
import pickle
def AddEnrollment():
    f = open("Enrollments.dat", "ab")
    rno = int(input("Roll no: "))
    name = input("Name: ")
    course = input("Course: ")
    fees = int(input("Fees: "))
    pickle.dump([rno, name, course, fees], f)
    f.close()

def UpdateFees():
    f = open("Enrollments.dat", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Data Science":
                rec[3] = 75000
            data.append(rec)
    except EOFError:
        f.close()
    f = open("Enrollments.dat", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.2CBSE 20265 marks

RESOURCES.DAT stores tuples (R_ID, R_Name, R_Expertise, Charges). Write Append() to input one record and add it to the file, and Update() to increase the Charges of every resource person by 500.

Answer
import pickle
def Append():
    f = open("RESOURCES.DAT", "ab")
    rid = input("ID: ")
    name = input("Name: ")
    exp = input("Expertise: ")
    ch = float(input("Charges: "))
    pickle.dump((rid, name, exp, ch), f)
    f.close()

def Update():
    f = open("RESOURCES.DAT", "rb")
    data = []
    try:
        while True:
            r = pickle.load(f)
            data.append((r[0], r[1], r[2], r[3] + 500))   # a tuple cannot be changed, so make a new one
    except EOFError:
        f.close()
    f = open("RESOURCES.DAT", "wb")
    for r in data:
        pickle.dump(r, f)
    f.close()
E1.3CBSE 20255 marks

PASSENGERS.DAT stores records [PNR, name, boarding station, destination, fare]. Write Create() to add a record, SearchDestn(D) to display the passengers going to D, and UpdateFare() to increase every fare by 5%.

Answer
import pickle
def Create():
    f = open("PASSENGERS.DAT", "ab")
    pnr = input("PNR: ")
    name = input("Name: ")
    brd = input("Boarding: ")
    dest = input("Destination: ")
    fare = float(input("Fare: "))
    pickle.dump([pnr, name, brd, dest, fare], f)
    f.close()

def SearchDestn(D):
    f = open("PASSENGERS.DAT", "rb")
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] == D:
                print(rec)
    except EOFError:
        f.close()

def UpdateFare():
    f = open("PASSENGERS.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            rec[4] = rec[4] * 1.05
            data.append(rec)
    except EOFError:
        f.close()
    f = open("PASSENGERS.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.4Practice5 marks

STUDENT.DAT stores records [RNo, Name, Marks]. Write AddRec() to add one record and CountPass() to return the number of students with marks 33 or more.

Answer
import pickle
def AddRec():
    f = open("STUDENT.DAT", "ab")
    rno = int(input("Roll no: "))
    name = input("Name: ")
    marks = int(input("Marks: "))
    pickle.dump([rno, name, marks], f)
    f.close()

def CountPass():
    f = open("STUDENT.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] >= 33:
                c += 1
    except EOFError:
        f.close()
    return c
E1.5Practice5 marks

EMP.DAT stores dictionaries of the form {'ENo': ..., 'Name': ..., 'Salary': ...}. Write AddEmp() to add one record and HighPaid() to display the employees whose salary is more than 50000.

Answer
import pickle
def AddEmp():
    f = open("EMP.DAT", "ab")
    D = {}
    D["ENo"] = int(input("Emp no: "))
    D["Name"] = input("Name: ")
    D["Salary"] = int(input("Salary: "))
    pickle.dump(D, f)
    f.close()

def HighPaid():
    f = open("EMP.DAT", "rb")
    try:
        while True:
            D = pickle.load(f)
            if D["Salary"] > 50000:
                print(D["ENo"], D["Name"], D["Salary"])
    except EOFError:
        f.close()
E1.6Practice5 marks

ITEM.DAT stores records [ICode, IName, Price]. Write Search(code) to display the record with that item code or "Not found", and Delete(code) to remove that record from the file.

Answer
import pickle
def Search(code):
    f = open("ITEM.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == code:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def Delete(code):
    f = open("ITEM.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != code:           # keep all the other records
                data.append(rec)
    except EOFError:
        f.close()
    f = open("ITEM.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.7Practice5 marks

BOOK.DAT stores records [BNo, Title, Price]. Write CopyCostly() to copy the books costing more than 500 into COSTLY.DAT and to return the number of records copied.

Answer
import pickle
def CopyCostly():
    f1 = open("BOOK.DAT", "rb")
    f2 = open("COSTLY.DAT", "wb")
    c = 0
    try:
        while True:
            rec = pickle.load(f1)
            if rec[2] > 500:
                pickle.dump(rec, f2)
                c += 1
    except EOFError:
        f1.close()
        f2.close()
    return c
E1.8Practice5 marks

PLAYER.DAT stores records [PID, PName, Runs]. Write AddRuns(pid, r) to add r runs to the player with ID pid, and ShowAll() to display all the records.

Answer
import pickle
def AddRuns(pid, r):
    f = open("PLAYER.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == pid:
                rec[2] = rec[2] + r
            data.append(rec)
    except EOFError:
        f.close()
    f = open("PLAYER.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("PLAYER.DAT", "rb")
    try:
        while True:
            print(pickle.load(f))
    except EOFError:
        f.close()
E1.9Practice5 marks

HOTEL.DAT stores records [RoomNo, Guest, Days, Rent]. Write Bill() to display each guest's name with the bill (Days x Rent) and to print the total collection.

Answer
import pickle
def Bill():
    f = open("HOTEL.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            amt = rec[2] * rec[3]
            print(rec[1], amt)
            total += amt
    except EOFError:
        f.close()
    print("Total collection:", total)
E1.10Practice5 marks

MARKS.DAT stores one list of records, written with a single dump(): [[RNo, Name, Marks], ...]. Write Topper() to display the record with the highest marks, and Add(rec) to add a new record to the list and save it back.

Answer

When the whole list is stored with one dump(), one load() reads it back, so no loop or EOFError is needed.

import pickle
def Topper():
    f = open("MARKS.DAT", "rb")
    L = pickle.load(f)           # the whole list in one load
    f.close()
    top = L[0]
    for rec in L:
        if rec[2] > top[2]:
            top = rec
    print(top)

def Add(rec):
    f = open("MARKS.DAT", "rb")
    L = pickle.load(f)
    f.close()
    L.append(rec)
    f = open("MARKS.DAT", "wb")
    pickle.dump(L, f)
    f.close()
E1.11Practice5 marks

TOY.DAT stores records of the form [TID, TName, Category, Price]. Write AddToy() to input one record and add it to the file, and CountToy() to return the number of records whose Price is more than 500.

Answer
import pickle
def AddToy():
    f = open("TOY.DAT", "ab")
    tid = int(input("TID: "))
    tname = input("TName: ")
    category = input("Category: ")
    price = int(input("Price: "))
    pickle.dump([tid, tname, category, price], f)
    f.close()

def CountToy():
    f = open("TOY.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] > 500:
                c += 1
    except EOFError:
        f.close()
    return c
E1.12Practice5 marks

TOY.DAT stores records of the form [TID, TName, Category, Price]. Write SearchToy(n) to display the record whose TID is n, or "Not found", and UpdateToy() to increase the Price by 100 for the records whose Category is "Electronic".

Answer
import pickle
def SearchToy(n):
    f = open("TOY.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def UpdateToy():
    f = open("TOY.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Electronic":
                rec[3] = rec[3] + 100
            data.append(rec)
    except EOFError:
        f.close()
    f = open("TOY.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.13Practice5 marks

TOY.DAT stores records of the form [TID, TName, Category, Price]. Write DeleteToy(n) to remove the record whose TID is n, and ShowAll() to display all the records and then the total of Price.

Answer
import pickle
def DeleteToy(n):
    f = open("TOY.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != n:
                data.append(rec)
    except EOFError:
        f.close()
    f = open("TOY.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("TOY.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            print(rec)
            total += rec[3]
    except EOFError:
        f.close()
    print("Total Price:", total)
E1.14Practice5 marks

GYM.DAT stores records of the form [MNo, Name, Plan, Fee]. Write AddMember() to input one record and add it to the file, and CountMember() to return the number of records whose Fee is more than 2000.

Answer
import pickle
def AddMember():
    f = open("GYM.DAT", "ab")
    mno = int(input("MNo: "))
    name = input("Name: ")
    plan = input("Plan: ")
    fee = int(input("Fee: "))
    pickle.dump([mno, name, plan, fee], f)
    f.close()

def CountMember():
    f = open("GYM.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] > 2000:
                c += 1
    except EOFError:
        f.close()
    return c
E1.15Practice5 marks

GYM.DAT stores records of the form [MNo, Name, Plan, Fee]. Write SearchMember(n) to display the record whose MNo is n, or "Not found", and UpdateMember() to increase the Fee by 250 for the records whose Plan is "Gold".

Answer
import pickle
def SearchMember(n):
    f = open("GYM.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def UpdateMember():
    f = open("GYM.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Gold":
                rec[3] = rec[3] + 250
            data.append(rec)
    except EOFError:
        f.close()
    f = open("GYM.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.16Practice5 marks

GYM.DAT stores records of the form [MNo, Name, Plan, Fee]. Write DeleteMember(n) to remove the record whose MNo is n, and ShowAll() to display all the records and then the total of Fee.

Answer
import pickle
def DeleteMember(n):
    f = open("GYM.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != n:
                data.append(rec)
    except EOFError:
        f.close()
    f = open("GYM.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("GYM.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            print(rec)
            total += rec[3]
    except EOFError:
        f.close()
    print("Total Fee:", total)
E1.17Practice5 marks

LAPTOP.DAT stores records of the form [LNo, Model, Brand, Price]. Write AddLaptop() to input one record and add it to the file, and CountLaptop() to return the number of records whose Price is more than 40000.

Answer
import pickle
def AddLaptop():
    f = open("LAPTOP.DAT", "ab")
    lno = int(input("LNo: "))
    model = input("Model: ")
    brand = input("Brand: ")
    price = int(input("Price: "))
    pickle.dump([lno, model, brand, price], f)
    f.close()

def CountLaptop():
    f = open("LAPTOP.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] > 40000:
                c += 1
    except EOFError:
        f.close()
    return c
E1.18Practice5 marks

LAPTOP.DAT stores records of the form [LNo, Model, Brand, Price]. Write SearchLaptop(n) to display the record whose LNo is n, or "Not found", and UpdateLaptop() to increase the Price by 1500 for the records whose Brand is "Zen".

Answer
import pickle
def SearchLaptop(n):
    f = open("LAPTOP.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def UpdateLaptop():
    f = open("LAPTOP.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Zen":
                rec[3] = rec[3] + 1500
            data.append(rec)
    except EOFError:
        f.close()
    f = open("LAPTOP.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.19Practice5 marks

LAPTOP.DAT stores records of the form [LNo, Model, Brand, Price]. Write DeleteLaptop(n) to remove the record whose LNo is n, and ShowAll() to display all the records and then the total of Price.

Answer
import pickle
def DeleteLaptop(n):
    f = open("LAPTOP.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != n:
                data.append(rec)
    except EOFError:
        f.close()
    f = open("LAPTOP.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("LAPTOP.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            print(rec)
            total += rec[3]
    except EOFError:
        f.close()
    print("Total Price:", total)
E1.20Practice5 marks

CROP.DAT stores records of the form [CNo, Crop, Season, Quintals]. Write AddCrop() to input one record and add it to the file, and CountCrop() to return the number of records whose Quintals is more than 30.

Answer
import pickle
def AddCrop():
    f = open("CROP.DAT", "ab")
    cno = int(input("CNo: "))
    crop = input("Crop: ")
    season = input("Season: ")
    quintals = int(input("Quintals: "))
    pickle.dump([cno, crop, season, quintals], f)
    f.close()

def CountCrop():
    f = open("CROP.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] > 30:
                c += 1
    except EOFError:
        f.close()
    return c
E1.21Practice5 marks

CROP.DAT stores records of the form [CNo, Crop, Season, Quintals]. Write SearchCrop(n) to display the record whose CNo is n, or "Not found", and UpdateCrop() to increase the Quintals by 5 for the records whose Season is "Rabi".

Answer
import pickle
def SearchCrop(n):
    f = open("CROP.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def UpdateCrop():
    f = open("CROP.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Rabi":
                rec[3] = rec[3] + 5
            data.append(rec)
    except EOFError:
        f.close()
    f = open("CROP.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.22Practice5 marks

CROP.DAT stores records of the form [CNo, Crop, Season, Quintals]. Write DeleteCrop(n) to remove the record whose CNo is n, and ShowAll() to display all the records and then the total of Quintals.

Answer
import pickle
def DeleteCrop(n):
    f = open("CROP.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != n:
                data.append(rec)
    except EOFError:
        f.close()
    f = open("CROP.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("CROP.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            print(rec)
            total += rec[3]
    except EOFError:
        f.close()
    print("Total Quintals:", total)
E1.23Practice5 marks

FILM.DAT stores records of the form [FNo, Title, Language, Tickets]. Write AddFilm() to input one record and add it to the file, and CountFilm() to return the number of records whose Tickets is more than 400.

Answer
import pickle
def AddFilm():
    f = open("FILM.DAT", "ab")
    fno = int(input("FNo: "))
    title = input("Title: ")
    language = input("Language: ")
    tickets = int(input("Tickets: "))
    pickle.dump([fno, title, language, tickets], f)
    f.close()

def CountFilm():
    f = open("FILM.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] > 400:
                c += 1
    except EOFError:
        f.close()
    return c
E1.24Practice5 marks

FILM.DAT stores records of the form [FNo, Title, Language, Tickets]. Write SearchFilm(n) to display the record whose FNo is n, or "Not found", and UpdateFilm() to increase the Tickets by 50 for the records whose Language is "Hindi".

Answer
import pickle
def SearchFilm(n):
    f = open("FILM.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def UpdateFilm():
    f = open("FILM.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Hindi":
                rec[3] = rec[3] + 50
            data.append(rec)
    except EOFError:
        f.close()
    f = open("FILM.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.25Practice5 marks

FILM.DAT stores records of the form [FNo, Title, Language, Tickets]. Write DeleteFilm(n) to remove the record whose FNo is n, and ShowAll() to display all the records and then the total of Tickets.

Answer
import pickle
def DeleteFilm(n):
    f = open("FILM.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != n:
                data.append(rec)
    except EOFError:
        f.close()
    f = open("FILM.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("FILM.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            print(rec)
            total += rec[3]
    except EOFError:
        f.close()
    print("Total Tickets:", total)
E1.26Practice5 marks

ROOM.DAT stores records of the form [RNo, Guest, RoomType, Rent]. Write AddRoom() to input one record and add it to the file, and CountRoom() to return the number of records whose Rent is more than 2000.

Answer
import pickle
def AddRoom():
    f = open("ROOM.DAT", "ab")
    rno = int(input("RNo: "))
    guest = input("Guest: ")
    roomtype = input("RoomType: ")
    rent = int(input("Rent: "))
    pickle.dump([rno, guest, roomtype, rent], f)
    f.close()

def CountRoom():
    f = open("ROOM.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] > 2000:
                c += 1
    except EOFError:
        f.close()
    return c
E1.27Practice5 marks

ROOM.DAT stores records of the form [RNo, Guest, RoomType, Rent]. Write SearchRoom(n) to display the record whose RNo is n, or "Not found", and UpdateRoom() to increase the Rent by 200 for the records whose RoomType is "Deluxe".

Answer
import pickle
def SearchRoom(n):
    f = open("ROOM.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def UpdateRoom():
    f = open("ROOM.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Deluxe":
                rec[3] = rec[3] + 200
            data.append(rec)
    except EOFError:
        f.close()
    f = open("ROOM.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.28Practice5 marks

ROOM.DAT stores records of the form [RNo, Guest, RoomType, Rent]. Write DeleteRoom(n) to remove the record whose RNo is n, and ShowAll() to display all the records and then the total of Rent.

Answer
import pickle
def DeleteRoom(n):
    f = open("ROOM.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != n:
                data.append(rec)
    except EOFError:
        f.close()
    f = open("ROOM.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("ROOM.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            print(rec)
            total += rec[3]
    except EOFError:
        f.close()
    print("Total Rent:", total)
E1.29Practice5 marks

CAB.DAT stores records of the form [CabNo, Driver, City, Fare]. Write AddCab() to input one record and add it to the file, and CountCab() to return the number of records whose Fare is more than 800.

Answer
import pickle
def AddCab():
    f = open("CAB.DAT", "ab")
    cabno = int(input("CabNo: "))
    driver = input("Driver: ")
    city = input("City: ")
    fare = int(input("Fare: "))
    pickle.dump([cabno, driver, city, fare], f)
    f.close()

def CountCab():
    f = open("CAB.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] > 800:
                c += 1
    except EOFError:
        f.close()
    return c
E1.30Practice5 marks

CAB.DAT stores records of the form [CabNo, Driver, City, Fare]. Write SearchCab(n) to display the record whose CabNo is n, or "Not found", and UpdateCab() to increase the Fare by 50 for the records whose City is "Jaipur".

Answer
import pickle
def SearchCab(n):
    f = open("CAB.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def UpdateCab():
    f = open("CAB.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Jaipur":
                rec[3] = rec[3] + 50
            data.append(rec)
    except EOFError:
        f.close()
    f = open("CAB.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.31Practice5 marks

CAB.DAT stores records of the form [CabNo, Driver, City, Fare]. Write DeleteCab(n) to remove the record whose CabNo is n, and ShowAll() to display all the records and then the total of Fare.

Answer
import pickle
def DeleteCab(n):
    f = open("CAB.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != n:
                data.append(rec)
    except EOFError:
        f.close()
    f = open("CAB.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("CAB.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            print(rec)
            total += rec[3]
    except EOFError:
        f.close()
    print("Total Fare:", total)
E1.32Practice5 marks

QUIZ.DAT stores records of the form [QNo, Team, House, Score]. Write AddTeam() to input one record and add it to the file, and CountTeam() to return the number of records whose Score is more than 50.

Answer
import pickle
def AddTeam():
    f = open("QUIZ.DAT", "ab")
    qno = int(input("QNo: "))
    team = input("Team: ")
    house = input("House: ")
    score = int(input("Score: "))
    pickle.dump([qno, team, house, score], f)
    f.close()

def CountTeam():
    f = open("QUIZ.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] > 50:
                c += 1
    except EOFError:
        f.close()
    return c
E1.33Practice5 marks

QUIZ.DAT stores records of the form [QNo, Team, House, Score]. Write SearchTeam(n) to display the record whose QNo is n, or "Not found", and UpdateTeam() to increase the Score by 5 for the records whose House is "Shivaji".

Answer
import pickle
def SearchTeam(n):
    f = open("QUIZ.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def UpdateTeam():
    f = open("QUIZ.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Shivaji":
                rec[3] = rec[3] + 5
            data.append(rec)
    except EOFError:
        f.close()
    f = open("QUIZ.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.34Practice5 marks

QUIZ.DAT stores records of the form [QNo, Team, House, Score]. Write DeleteTeam(n) to remove the record whose QNo is n, and ShowAll() to display all the records and then the total of Score.

Answer
import pickle
def DeleteTeam(n):
    f = open("QUIZ.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != n:
                data.append(rec)
    except EOFError:
        f.close()
    f = open("QUIZ.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("QUIZ.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            print(rec)
            total += rec[3]
    except EOFError:
        f.close()
    print("Total Score:", total)
E1.35Practice5 marks

MEDAL.DAT stores records of the form [MNo, Athlete, Event, Points]. Write AddAthlete() to input one record and add it to the file, and CountAthlete() to return the number of records whose Points is more than 70.

Answer
import pickle
def AddAthlete():
    f = open("MEDAL.DAT", "ab")
    mno = int(input("MNo: "))
    athlete = input("Athlete: ")
    event = input("Event: ")
    points = int(input("Points: "))
    pickle.dump([mno, athlete, event, points], f)
    f.close()

def CountAthlete():
    f = open("MEDAL.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] > 70:
                c += 1
    except EOFError:
        f.close()
    return c
E1.36Practice5 marks

MEDAL.DAT stores records of the form [MNo, Athlete, Event, Points]. Write SearchAthlete(n) to display the record whose MNo is n, or "Not found", and UpdateAthlete() to increase the Points by 10 for the records whose Event is "Sprint".

Answer
import pickle
def SearchAthlete(n):
    f = open("MEDAL.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def UpdateAthlete():
    f = open("MEDAL.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Sprint":
                rec[3] = rec[3] + 10
            data.append(rec)
    except EOFError:
        f.close()
    f = open("MEDAL.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.37Practice5 marks

MEDAL.DAT stores records of the form [MNo, Athlete, Event, Points]. Write DeleteAthlete(n) to remove the record whose MNo is n, and ShowAll() to display all the records and then the total of Points.

Answer
import pickle
def DeleteAthlete(n):
    f = open("MEDAL.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != n:
                data.append(rec)
    except EOFError:
        f.close()
    f = open("MEDAL.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("MEDAL.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            print(rec)
            total += rec[3]
    except EOFError:
        f.close()
    print("Total Points:", total)
E1.38Practice5 marks

NURSERY.DAT stores records of the form [PNo, Plant, Kind, Stock]. Write AddPlant() to input one record and add it to the file, and CountPlant() to return the number of records whose Stock is more than 40.

Answer
import pickle
def AddPlant():
    f = open("NURSERY.DAT", "ab")
    pno = int(input("PNo: "))
    plant = input("Plant: ")
    kind = input("Kind: ")
    stock = int(input("Stock: "))
    pickle.dump([pno, plant, kind, stock], f)
    f.close()

def CountPlant():
    f = open("NURSERY.DAT", "rb")
    c = 0
    try:
        while True:
            rec = pickle.load(f)
            if rec[3] > 40:
                c += 1
    except EOFError:
        f.close()
    return c
E1.39Practice5 marks

NURSERY.DAT stores records of the form [PNo, Plant, Kind, Stock]. Write SearchPlant(n) to display the record whose PNo is n, or "Not found", and UpdatePlant() to increase the Stock by 10 for the records whose Kind is "Tree".

Answer
import pickle
def SearchPlant(n):
    f = open("NURSERY.DAT", "rb")
    found = False
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] == n:
                print(rec)
                found = True
    except EOFError:
        f.close()
    if not found:
        print("Not found")

def UpdatePlant():
    f = open("NURSERY.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[2] == "Tree":
                rec[3] = rec[3] + 10
            data.append(rec)
    except EOFError:
        f.close()
    f = open("NURSERY.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()
E1.40Practice5 marks

NURSERY.DAT stores records of the form [PNo, Plant, Kind, Stock]. Write DeletePlant(n) to remove the record whose PNo is n, and ShowAll() to display all the records and then the total of Stock.

Answer
import pickle
def DeletePlant(n):
    f = open("NURSERY.DAT", "rb")
    data = []
    try:
        while True:
            rec = pickle.load(f)
            if rec[0] != n:
                data.append(rec)
    except EOFError:
        f.close()
    f = open("NURSERY.DAT", "wb")
    for rec in data:
        pickle.dump(rec, f)
    f.close()

def ShowAll():
    f = open("NURSERY.DAT", "rb")
    total = 0
    try:
        while True:
            rec = pickle.load(f)
            print(rec)
            total += rec[3]
    except EOFError:
        f.close()
    print("Total Stock:", total)
E2Network case study5 marks · 40 questions
E2.1SQP 2026-275 marks

AKA University, Raipur.

The campus has four blocks: Law, Business, Technology and HR Centre. The HR Centre has the most computers (120). The HR Centre to Law link is 120 m and the HR Centre to Business link is 105 m. The university also has a study centre in Delhi. (Full distance table: see the sample paper.) Suggest:

  1. The block for the server
  2. The topology
  3. Where to place repeaters and switches
  4. The best guided medium to connect the Delhi centre
  5. The protocol for a face-to-face digital meeting, or the use of VoIP.
Answer
  1. Server: HR Centre, because it has the most computers.
  2. Topology: star, with every block connected to the HR Centre.
  3. Repeater: on the HR Centre to Law and HR Centre to Business links, because both are longer than 100 m. Switch: one in every block.
  4. Guided medium for Delhi: optical fibre.
  5. Digital meeting: VoIP. It carries voice and video calls over the Internet.
E2.2CBSE 20265 marks

Sanjeevani University, Amritsar. It has four blocks, as shown in the layout.

Layout of the blocks

60 m150 m160 m120 m80 m40 mADMIN25 computersACADEMIC600 computersHOSTEL120 computersSPORTS50 computers

Number of computers

BlockComputers
ADMIN25
ACADEMIC600
HOSTEL120
SPORTS50

Distance between blocks

FromToDistance
ADMINACADEMIC60 m
ADMINHOSTEL160 m
ADMINSPORTS80 m
ACADEMICHOSTEL40 m
ACADEMICSPORTS120 m
HOSTELSPORTS150 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. Two wired media
  4. The medium used in FM radio
  5. The protocol for audio-visual communication, or the place for a repeater.
Answer

Cable layout (star). R marks a repeater.

60 m40 m120 mRADMINswitchACADEMICSERVER + switchHOSTELswitchSPORTSswitch
  1. Server: ACADEMIC, because it has the most computers (600).
  2. Layout: star from ACADEMIC to ADMIN (60 m), HOSTEL (40 m) and SPORTS (120 m).
  3. Wired media: twisted pair (Ethernet) cable and optical fibre.
  4. FM radio: radio waves.
  5. Protocol: VoIP. Repeater: between ACADEMIC and SPORTS, the only link longer than 100 m.
E2.3CBSE 20255 marks

Health centre, Vijayawada (head office in Nagpur).

The centre has four blocks: ADMIN, PSYCHIATRY, PSYCHOLOGY and ICU. (Distances and computer counts: see the 2025 paper.) Suggest:

  1. The block for the server
  2. The device to connect the computers inside each block
  3. The cable layout
  4. The place for the device that gives Internet to all the computers
  5. How the manager in Nagpur can use a computer of the ADMIN block from a distance, or the type of network inside the centre.
Answer
  1. Server: the block with the most computers (ADMIN in the commonly accepted solution).
  2. Device in each block: switch.
  3. Layout: star, from the server block to the other three blocks.
  4. Router / modem: in the server block.
  5. Remote access: remote login (TELNET or SSH). Network inside the centre: LAN.
E2.4Practice5 marks

Senior Secondary School, Jaipur. It has four blocks, as shown in the layout.

Layout of the blocks

45 m90 m70 m150 m130 m60 mSENIOR120 computersJUNIOR40 computersADMIN25 computersHOSTEL60 computers

Number of computers

BlockComputers
SENIOR120
JUNIOR40
ADMIN25
HOSTEL60

Distance between blocks

FromToDistance
SENIORJUNIOR45 m
SENIORADMIN70 m
SENIORHOSTEL130 m
JUNIORADMIN60 m
JUNIORHOSTEL150 m
ADMINHOSTEL90 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to install in every block
  5. The type of network formed when the school is linked with its head office in Mumbai.
Answer

Cable layout (star). R marks a repeater.

45 m70 m130 mRSENIORSERVER + switchJUNIORswitchADMINswitchHOSTELswitch
  1. Server: SENIOR block (120 computers, the most).
  2. Layout: star from SENIOR to JUNIOR (45 m), ADMIN (70 m) and HOSTEL (130 m).
  3. Repeater: between SENIOR and HOSTEL (130 m, more than 100 m).
  4. Device in every block: switch.
  5. Jaipur to Mumbai: WAN.
E2.5Practice5 marks

City Hospital, Lucknow. It has four blocks, as shown in the layout.

Layout of the blocks

70 m40 m55 m125 m90 m110 mOPD60 computersLAB30 computersWARDS150 computersPHARMACY20 computers

Number of computers

BlockComputers
OPD60
LAB30
WARDS150
PHARMACY20

Distance between blocks

FromToDistance
OPDLAB70 m
OPDWARDS55 m
OPDPHARMACY90 m
LABWARDS110 m
LABPHARMACY125 m
WARDSPHARMACY40 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The hardware or software that protects the network from unauthorised access
  5. The protocol used to send test reports to patients by e-mail.
Answer

Cable layout (star). R marks a repeater.

55 m110 mR40 mOPDswitchLABswitchWARDSSERVER + switchPHARMACYswitch
  1. Server: WARDS block (150 computers).
  2. Layout: star from WARDS to OPD (55 m), LAB (110 m) and PHARMACY (40 m).
  3. Repeater: between WARDS and LAB (110 m).
  4. Protection: firewall.
  5. Sending e-mail: SMTP.
E2.6Practice5 marks

Software company, Pune. It has four blocks, as shown in the layout.

Layout of the blocks

30 m50 m95 m105 m140 m60 mDEVELOPMENT200 computersTESTING80 computersHR25 computersFINANCE35 computers

Number of computers

BlockComputers
DEVELOPMENT200
TESTING80
HR25
FINANCE35

Distance between blocks

FromToDistance
DEVELOPMENTTESTING30 m
DEVELOPMENTHR95 m
DEVELOPMENTFINANCE140 m
TESTINGHR60 m
TESTINGFINANCE105 m
HRFINANCE50 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. Hub or switch for each block, with a reason
  4. The place for a repeater
  5. The protocol to upload large project files to the client's server.
Answer

Cable layout (star). R marks a repeater.

30 m95 m140 mRDEVELOPMENTSERVER + switchTESTINGswitchHRswitchFINANCEswitch
  1. Server: DEVELOPMENT block (200 computers).
  2. Layout: star from DEVELOPMENT to TESTING (30 m), HR (95 m) and FINANCE (140 m).
  3. Switch, because it sends data only to the destination computer, so the network is faster.
  4. Repeater: between DEVELOPMENT and FINANCE (140 m).
  5. File upload: FTP (File Transfer Protocol).
E2.7Practice5 marks

State University, Bhopal. It has four blocks, as shown in the layout.

Layout of the blocks

65 m160 m75 m85 m135 m115 mLIBRARY50 computersSCIENCE180 computersARTS70 computersOFFICE40 computers

Number of computers

BlockComputers
LIBRARY50
SCIENCE180
ARTS70
OFFICE40

Distance between blocks

FromToDistance
LIBRARYSCIENCE65 m
LIBRARYARTS75 m
LIBRARYOFFICE135 m
SCIENCEARTS115 m
SCIENCEOFFICE85 m
ARTSOFFICE160 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The most suitable wired medium for high-speed links between the blocks
  5. The type of network formed inside the campus.
Answer

Cable layout (star). R marks a repeater.

65 m115 mR85 mLIBRARYswitchSCIENCESERVER + switchARTSswitchOFFICEswitch
  1. Server: SCIENCE block (180 computers).
  2. Layout: star from SCIENCE to LIBRARY (65 m), ARTS (115 m) and OFFICE (85 m).
  3. Repeater: between SCIENCE and ARTS (115 m).
  4. Medium: optical fibre.
  5. Inside the campus: LAN.
E2.8Practice5 marks

Bank training centre, Kolkata. It has four blocks, as shown in the layout.

Layout of the blocks

50 m60 m95 m80 m110 m125 mTRAINING90 computersEXAM140 computersGUEST HOUSE30 computersRECORDS45 computers

Number of computers

BlockComputers
TRAINING90
EXAM140
GUEST HOUSE30
RECORDS45

Distance between blocks

FromToDistance
TRAININGEXAM50 m
TRAININGGUEST HOUSE95 m
TRAININGRECORDS110 m
EXAMGUEST HOUSE125 m
EXAMRECORDS80 m
GUEST HOUSERECORDS60 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device that connects this network to the Internet, and its place
  5. The protocol that lets an officer in Delhi log in to a computer of the centre.
Answer

Cable layout (star). R marks a repeater.

50 m125 mR80 mTRAININGswitchEXAMSERVER + switchGUEST HOUSEswitchRECORDSswitch
  1. Server: EXAM block (140 computers).
  2. Layout: star from EXAM to TRAINING (50 m), GUEST HOUSE (125 m) and RECORDS (80 m).
  3. Repeater: between EXAM and GUEST HOUSE (125 m).
  4. Router (with modem): in the EXAM block, where the server is.
  5. Remote login: TELNET.
E2.9Practice5 marks

Publishing house, Chandigarh. It has four blocks, as shown in the layout.

Layout of the blocks

40 m55 m70 m145 m100 m90 mEDITORIAL75 computersDESIGN110 computersPRINTING35 computersSTORE15 computers

Number of computers

BlockComputers
EDITORIAL75
DESIGN110
PRINTING35
STORE15

Distance between blocks

FromToDistance
EDITORIALDESIGN40 m
EDITORIALPRINTING70 m
EDITORIALSTORE100 m
DESIGNPRINTING90 m
DESIGNSTORE145 m
PRINTINGSTORE55 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The cheapest wired medium for the computers inside a block
  5. The service used by the editors for a video meeting with authors in other cities.
Answer

Cable layout (star). R marks a repeater.

40 m90 m145 mREDITORIALswitchDESIGNSERVER + switchPRINTINGswitchSTOREswitch
  1. Server: DESIGN block (110 computers).
  2. Layout: star from DESIGN to EDITORIAL (40 m), PRINTING (90 m) and STORE (145 m).
  3. Repeater: between DESIGN and STORE (145 m).
  4. Inside a block: twisted pair (Ethernet) cable.
  5. Video meeting: video conferencing, which works on VoIP.
E2.10Practice5 marks

Sports academy, Guwahati. The academy also has a camp in a hilly area 40 km away. It has four blocks, as shown in the layout.

Layout of the blocks

60 m45 m85 m75 m120 m105 mCOACHING55 computersHOSTEL95 computersMEDICAL20 computersOFFICE30 computers

Number of computers

BlockComputers
COACHING55
HOSTEL95
MEDICAL20
OFFICE30

Distance between blocks

FromToDistance
COACHINGHOSTEL60 m
COACHINGMEDICAL85 m
COACHINGOFFICE120 m
HOSTELMEDICAL105 m
HOSTELOFFICE75 m
MEDICALOFFICE45 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The medium to connect the hilly camp where cables cannot be laid
  5. The protocol for making voice calls between the academy and the camp over the Internet.
Answer

Cable layout (star). R marks a repeater.

60 m105 mR75 mCOACHINGswitchHOSTELSERVER + switchMEDICALswitchOFFICEswitch
  1. Server: HOSTEL block (95 computers).
  2. Layout: star from HOSTEL to COACHING (60 m), MEDICAL (105 m) and OFFICE (75 m).
  3. Repeater: between HOSTEL and MEDICAL (105 m).
  4. Hilly camp: radio waves (wireless), because they need no cable and no line of sight.
  5. Voice calls over the Internet: VoIP (Voice over Internet Protocol).
E2.11Practice5 marks

Vidya Public School, Nagpur. It has four blocks, as shown in the layout.

Layout of the blocks

130 m170 m80 m130 m155 m90 mADMIN45 computersLIBRARY160 computersSCIENCE40 computersHOSTEL15 computers

Number of computers

BlockComputers
ADMIN45
LIBRARY160
SCIENCE40
HOSTEL15

Distance between blocks

FromToDistance
ADMINLIBRARY130 m
ADMINSCIENCE80 m
ADMINHOSTEL155 m
LIBRARYSCIENCE90 m
LIBRARYHOSTEL130 m
SCIENCEHOSTEL170 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The type of network formed between this campus and its branch in another city.
Answer

Cable layout (star). R marks a repeater.

130 mR90 m130 mRADMINswitchLIBRARYSERVER + switchSCIENCEswitchHOSTELswitch
  1. Server: LIBRARY block, because it has the most computers (160).
  2. Layout: star from LIBRARY to ADMIN (130 m), SCIENCE (90 m), HOSTEL (130 m).
  3. Repeater: between LIBRARY and ADMIN (130 m) and between LIBRARY and HOSTEL (130 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): WAN (Wide Area Network).
E2.12Practice5 marks

Sunrise Textiles, Surat. It has four blocks, as shown in the layout.

Layout of the blocks

55 m40 m70 m125 m75 m135 mHR70 computersSALES140 computersPRODUCTION125 computersSTORE205 computers

Number of computers

BlockComputers
HR70
SALES140
PRODUCTION125
STORE205

Distance between blocks

FromToDistance
HRSALES55 m
HRPRODUCTION70 m
HRSTORE75 m
SALESPRODUCTION135 m
SALESSTORE125 m
PRODUCTIONSTORE40 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for video conferencing with the branch office.
Answer

Cable layout (star). R marks a repeater.

75 m125 mR40 mHRswitchSALESswitchPRODUCTIONswitchSTORESERVER + switch
  1. Server: STORE block, because it has the most computers (205).
  2. Layout: star from STORE to HR (75 m), SALES (125 m), PRODUCTION (40 m).
  3. Repeater: between STORE and SALES (125 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): VoIP (Voice over Internet Protocol).
E2.13Practice5 marks

Lifeline Hospital, Patna. It has four blocks, as shown in the layout.

Layout of the blocks

40 m175 m70 m160 m180 m150 mOPD215 computersLAB225 computersWARD120 computersPHARMACY110 computers

Number of computers

BlockComputers
OPD215
LAB225
WARD120
PHARMACY110

Distance between blocks

FromToDistance
OPDLAB40 m
OPDWARD70 m
OPDPHARMACY180 m
LABWARD150 m
LABPHARMACY160 m
WARDPHARMACY175 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The hardware or software that protects the network from unauthorised access.
Answer

Cable layout (star). R marks a repeater.

40 m150 mR160 mROPDswitchLABSERVER + switchWARDswitchPHARMACYswitch
  1. Server: LAB block, because it has the most computers (225).
  2. Layout: star from LAB to OPD (40 m), WARD (150 m), PHARMACY (160 m).
  3. Repeater: between LAB and WARD (150 m) and between LAB and PHARMACY (160 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): Firewall.
E2.14Practice5 marks

TechNova Institute, Hyderabad. It has four blocks, as shown in the layout.

Layout of the blocks

65 m160 m55 m80 m145 m170 mRECEPTION220 computersTRAINING95 computersDATA CENTRE150 computersCANTEEN175 computers

Number of computers

BlockComputers
RECEPTION220
TRAINING95
DATA CENTRE150
CANTEEN175

Distance between blocks

FromToDistance
RECEPTIONTRAINING65 m
RECEPTIONDATA CENTRE55 m
RECEPTIONCANTEEN145 m
TRAININGDATA CENTRE170 m
TRAININGCANTEEN80 m
DATA CENTRECANTEEN160 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The fastest wired medium to connect the blocks.
Answer

Cable layout (star). R marks a repeater.

65 m55 m145 mRRECEPTIONSERVER + switchTRAININGswitchDATA CENTREswitchCANTEENswitch
  1. Server: RECEPTION block, because it has the most computers (220).
  2. Layout: star from RECEPTION to TRAINING (65 m), DATA CENTRE (55 m), CANTEEN (145 m).
  3. Repeater: between RECEPTION and CANTEEN (145 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): Optical fibre.
E2.15Practice5 marks

Green Valley Polytechnic, Dehradun. It has four blocks, as shown in the layout.

Layout of the blocks

110 m90 m45 m95 m70 m150 mMAIN30 computersANNEXE115 computersWORKSHOP165 computersGUEST HOUSE95 computers

Number of computers

BlockComputers
MAIN30
ANNEXE115
WORKSHOP165
GUEST HOUSE95

Distance between blocks

FromToDistance
MAINANNEXE110 m
MAINWORKSHOP45 m
MAINGUEST HOUSE70 m
ANNEXEWORKSHOP150 m
ANNEXEGUEST HOUSE95 m
WORKSHOPGUEST HOUSE90 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for sending large files to the branch office.
Answer

Cable layout (star). R marks a repeater.

45 m150 mR90 mMAINswitchANNEXEswitchWORKSHOPSERVER + switchGUEST HOUSEswitch
  1. Server: WORKSHOP block, because it has the most computers (165).
  2. Layout: star from WORKSHOP to MAIN (45 m), ANNEXE (150 m), GUEST HOUSE (90 m).
  3. Repeater: between WORKSHOP and ANNEXE (150 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): FTP (File Transfer Protocol).
E2.16Practice5 marks

Daily Times Press, Bhopal. It has four blocks, as shown in the layout.

Layout of the blocks

120 m125 m40 m130 m40 m155 mEDITORIAL195 computersPRINTING40 computersMARKETING70 computersDISPATCH100 computers

Number of computers

BlockComputers
EDITORIAL195
PRINTING40
MARKETING70
DISPATCH100

Distance between blocks

FromToDistance
EDITORIALPRINTING120 m
EDITORIALMARKETING40 m
EDITORIALDISPATCH40 m
PRINTINGMARKETING155 m
PRINTINGDISPATCH130 m
MARKETINGDISPATCH125 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The type of network formed inside the campus.
Answer

Cable layout (star). R marks a repeater.

120 mR40 m40 mEDITORIALSERVER + switchPRINTINGswitchMARKETINGswitchDISPATCHswitch
  1. Server: EDITORIAL block, because it has the most computers (195).
  2. Layout: star from EDITORIAL to PRINTING (120 m), MARKETING (40 m), DISPATCH (40 m).
  3. Repeater: between EDITORIAL and PRINTING (120 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): LAN (Local Area Network).
E2.17Practice5 marks

Himalaya Sports School, Gangtok. It has four blocks, as shown in the layout.

Layout of the blocks

135 m130 m40 m120 m115 m30 mJUNIOR110 computersSENIOR200 computersSPORTS215 computersOFFICE175 computers

Number of computers

BlockComputers
JUNIOR110
SENIOR200
SPORTS215
OFFICE175

Distance between blocks

FromToDistance
JUNIORSENIOR135 m
JUNIORSPORTS40 m
JUNIOROFFICE115 m
SENIORSPORTS30 m
SENIOROFFICE120 m
SPORTSOFFICE130 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for logging in to a campus computer from another city.
Answer

Cable layout (star). R marks a repeater.

40 m30 m130 mRJUNIORswitchSENIORswitchSPORTSSERVER + switchOFFICEswitch
  1. Server: SPORTS block, because it has the most computers (215).
  2. Layout: star from SPORTS to JUNIOR (40 m), SENIOR (30 m), OFFICE (130 m).
  3. Repeater: between SPORTS and OFFICE (130 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): TELNET (remote login).
E2.18Practice5 marks

Orbit Labs, Bengaluru. It has four blocks, as shown in the layout.

Layout of the blocks

75 m100 m110 m105 m90 m160 mRESEARCH120 computersDESIGN215 computersTESTING130 computersACCOUNTS175 computers

Number of computers

BlockComputers
RESEARCH120
DESIGN215
TESTING130
ACCOUNTS175

Distance between blocks

FromToDistance
RESEARCHDESIGN75 m
RESEARCHTESTING110 m
RESEARCHACCOUNTS90 m
DESIGNTESTING160 m
DESIGNACCOUNTS105 m
TESTINGACCOUNTS100 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The type of network formed between this campus and its branch in another city.
Answer

Cable layout (star). R marks a repeater.

75 m160 mR105 mRRESEARCHswitchDESIGNSERVER + switchTESTINGswitchACCOUNTSswitch
  1. Server: DESIGN block, because it has the most computers (215).
  2. Layout: star from DESIGN to RESEARCH (75 m), TESTING (160 m), ACCOUNTS (105 m).
  3. Repeater: between DESIGN and TESTING (160 m) and between DESIGN and ACCOUNTS (105 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): WAN (Wide Area Network).
E2.19Practice5 marks

City Degree College, Kanpur. It has four blocks, as shown in the layout.

Layout of the blocks

170 m30 m105 m125 m70 m65 mARTS80 computersCOMMERCE135 computersSCIENCE160 computersADMIN70 computers

Number of computers

BlockComputers
ARTS80
COMMERCE135
SCIENCE160
ADMIN70

Distance between blocks

FromToDistance
ARTSCOMMERCE170 m
ARTSSCIENCE105 m
ARTSADMIN70 m
COMMERCESCIENCE65 m
COMMERCEADMIN125 m
SCIENCEADMIN30 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for video conferencing with the branch office.
Answer

Cable layout (star). R marks a repeater.

105 mR65 m30 mARTSswitchCOMMERCEswitchSCIENCESERVER + switchADMINswitch
  1. Server: SCIENCE block, because it has the most computers (160).
  2. Layout: star from SCIENCE to ARTS (105 m), COMMERCE (65 m), ADMIN (30 m).
  3. Repeater: between SCIENCE and ARTS (105 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): VoIP (Voice over Internet Protocol).
E2.20Practice5 marks

QuickKart Logistics, Noida. It has four blocks, as shown in the layout.

Layout of the blocks

135 m85 m120 m60 m115 m50 mBILLING165 computersCUSTOMER CARE235 computersWAREHOUSE95 computersIT215 computers

Number of computers

BlockComputers
BILLING165
CUSTOMER CARE235
WAREHOUSE95
IT215

Distance between blocks

FromToDistance
BILLINGCUSTOMER CARE135 m
BILLINGWAREHOUSE120 m
BILLINGIT115 m
CUSTOMER CAREWAREHOUSE50 m
CUSTOMER CAREIT60 m
WAREHOUSEIT85 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The hardware or software that protects the network from unauthorised access.
Answer

Cable layout (star). R marks a repeater.

135 mR50 m60 mBILLINGswitchCUSTOMER CARESERVER + switchWAREHOUSEswitchITswitch
  1. Server: CUSTOMER CARE block, because it has the most computers (235).
  2. Layout: star from CUSTOMER CARE to BILLING (135 m), WAREHOUSE (50 m), IT (60 m).
  3. Repeater: between CUSTOMER CARE and BILLING (135 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): Firewall.
E2.21Practice5 marks

Saraswati Vidya Mandir, Ranchi. It has four blocks, as shown in the layout.

Layout of the blocks

155 m50 m40 m95 m75 m105 mADMIN250 computersLIBRARY225 computersSCIENCE85 computersHOSTEL45 computers

Number of computers

BlockComputers
ADMIN250
LIBRARY225
SCIENCE85
HOSTEL45

Distance between blocks

FromToDistance
ADMINLIBRARY155 m
ADMINSCIENCE40 m
ADMINHOSTEL75 m
LIBRARYSCIENCE105 m
LIBRARYHOSTEL95 m
SCIENCEHOSTEL50 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The fastest wired medium to connect the blocks.
Answer

Cable layout (star). R marks a repeater.

155 mR40 m75 mADMINSERVER + switchLIBRARYswitchSCIENCEswitchHOSTELswitch
  1. Server: ADMIN block, because it has the most computers (250).
  2. Layout: star from ADMIN to LIBRARY (155 m), SCIENCE (40 m), HOSTEL (75 m).
  3. Repeater: between ADMIN and LIBRARY (155 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): Optical fibre.
E2.22Practice5 marks

Bharat Auto Parts, Pune. It has four blocks, as shown in the layout.

Layout of the blocks

50 m70 m70 m95 m140 m125 mHR225 computersSALES95 computersPRODUCTION155 computersSTORE250 computers

Number of computers

BlockComputers
HR225
SALES95
PRODUCTION155
STORE250

Distance between blocks

FromToDistance
HRSALES50 m
HRPRODUCTION70 m
HRSTORE140 m
SALESPRODUCTION125 m
SALESSTORE95 m
PRODUCTIONSTORE70 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for sending large files to the branch office.
Answer

Cable layout (star). R marks a repeater.

140 mR95 m70 mHRswitchSALESswitchPRODUCTIONswitchSTORESERVER + switch
  1. Server: STORE block, because it has the most computers (250).
  2. Layout: star from STORE to HR (140 m), SALES (95 m), PRODUCTION (70 m).
  3. Repeater: between STORE and HR (140 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): FTP (File Transfer Protocol).
E2.23Practice5 marks

Arogya Medical Centre, Kochi. It has four blocks, as shown in the layout.

Layout of the blocks

95 m30 m160 m165 m130 m110 mOPD125 computersLAB90 computersWARD195 computersPHARMACY180 computers

Number of computers

BlockComputers
OPD125
LAB90
WARD195
PHARMACY180

Distance between blocks

FromToDistance
OPDLAB95 m
OPDWARD160 m
OPDPHARMACY130 m
LABWARD110 m
LABPHARMACY165 m
WARDPHARMACY30 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The type of network formed inside the campus.
Answer

Cable layout (star). R marks a repeater.

160 mR110 mR30 mOPDswitchLABswitchWARDSERVER + switchPHARMACYswitch
  1. Server: WARD block, because it has the most computers (195).
  2. Layout: star from WARD to OPD (160 m), LAB (110 m), PHARMACY (30 m).
  3. Repeater: between WARD and OPD (160 m) and between WARD and LAB (110 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): LAN (Local Area Network).
E2.24Practice5 marks

SkillUp Academy, Indore. It has four blocks, as shown in the layout.

Layout of the blocks

60 m60 m70 m120 m85 m165 mRECEPTION60 computersTRAINING140 computersDATA CENTRE200 computersCANTEEN110 computers

Number of computers

BlockComputers
RECEPTION60
TRAINING140
DATA CENTRE200
CANTEEN110

Distance between blocks

FromToDistance
RECEPTIONTRAINING60 m
RECEPTIONDATA CENTRE70 m
RECEPTIONCANTEEN85 m
TRAININGDATA CENTRE165 m
TRAININGCANTEEN120 m
DATA CENTRECANTEEN60 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for logging in to a campus computer from another city.
Answer

Cable layout (star). R marks a repeater.

70 m165 mR60 mRECEPTIONswitchTRAININGswitchDATA CENTRESERVER + switchCANTEENswitch
  1. Server: DATA CENTRE block, because it has the most computers (200).
  2. Layout: star from DATA CENTRE to RECEPTION (70 m), TRAINING (165 m), CANTEEN (60 m).
  3. Repeater: between DATA CENTRE and TRAINING (165 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): TELNET (remote login).
E2.25Practice5 marks

Ganga Engineering Works, Varanasi. It has four blocks, as shown in the layout.

Layout of the blocks

75 m45 m160 m160 m70 m60 mMAIN210 computersANNEXE135 computersWORKSHOP95 computersGUEST HOUSE230 computers

Number of computers

BlockComputers
MAIN210
ANNEXE135
WORKSHOP95
GUEST HOUSE230

Distance between blocks

FromToDistance
MAINANNEXE75 m
MAINWORKSHOP160 m
MAINGUEST HOUSE70 m
ANNEXEWORKSHOP60 m
ANNEXEGUEST HOUSE160 m
WORKSHOPGUEST HOUSE45 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The type of network formed between this campus and its branch in another city.
Answer

Cable layout (star). R marks a repeater.

70 m160 mR45 mMAINswitchANNEXEswitchWORKSHOPswitchGUEST HOUSESERVER + switch
  1. Server: GUEST HOUSE block, because it has the most computers (230).
  2. Layout: star from GUEST HOUSE to MAIN (70 m), ANNEXE (160 m), WORKSHOP (45 m).
  3. Repeater: between GUEST HOUSE and ANNEXE (160 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): WAN (Wide Area Network).
E2.26Practice5 marks

Navyug Publications, Chandigarh. It has four blocks, as shown in the layout.

Layout of the blocks

120 m70 m60 m165 m75 m120 mEDITORIAL55 computersPRINTING15 computersMARKETING140 computersDISPATCH225 computers

Number of computers

BlockComputers
EDITORIAL55
PRINTING15
MARKETING140
DISPATCH225

Distance between blocks

FromToDistance
EDITORIALPRINTING120 m
EDITORIALMARKETING60 m
EDITORIALDISPATCH75 m
PRINTINGMARKETING120 m
PRINTINGDISPATCH165 m
MARKETINGDISPATCH70 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for video conferencing with the branch office.
Answer

Cable layout (star). R marks a repeater.

75 m165 mR70 mEDITORIALswitchPRINTINGswitchMARKETINGswitchDISPATCHSERVER + switch
  1. Server: DISPATCH block, because it has the most computers (225).
  2. Layout: star from DISPATCH to EDITORIAL (75 m), PRINTING (165 m), MARKETING (70 m).
  3. Repeater: between DISPATCH and PRINTING (165 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): VoIP (Voice over Internet Protocol).
E2.27Practice5 marks

Delhi Model School, Delhi. It has four blocks, as shown in the layout.

Layout of the blocks

40 m170 m115 m70 m180 m95 mJUNIOR185 computersSENIOR140 computersSPORTS50 computersOFFICE220 computers

Number of computers

BlockComputers
JUNIOR185
SENIOR140
SPORTS50
OFFICE220

Distance between blocks

FromToDistance
JUNIORSENIOR40 m
JUNIORSPORTS115 m
JUNIOROFFICE180 m
SENIORSPORTS95 m
SENIOROFFICE70 m
SPORTSOFFICE170 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The hardware or software that protects the network from unauthorised access.
Answer

Cable layout (star). R marks a repeater.

180 mR70 m170 mRJUNIORswitchSENIORswitchSPORTSswitchOFFICESERVER + switch
  1. Server: OFFICE block, because it has the most computers (220).
  2. Layout: star from OFFICE to JUNIOR (180 m), SENIOR (70 m), SPORTS (170 m).
  3. Repeater: between OFFICE and JUNIOR (180 m) and between OFFICE and SPORTS (170 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): Firewall.
E2.28Practice5 marks

Pixel Design Studio, Mumbai. It has four blocks, as shown in the layout.

Layout of the blocks

120 m40 m80 m50 m130 m60 mRESEARCH35 computersDESIGN75 computersTESTING135 computersACCOUNTS180 computers

Number of computers

BlockComputers
RESEARCH35
DESIGN75
TESTING135
ACCOUNTS180

Distance between blocks

FromToDistance
RESEARCHDESIGN120 m
RESEARCHTESTING80 m
RESEARCHACCOUNTS130 m
DESIGNTESTING60 m
DESIGNACCOUNTS50 m
TESTINGACCOUNTS40 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The fastest wired medium to connect the blocks.
Answer

Cable layout (star). R marks a repeater.

130 mR50 m40 mRESEARCHswitchDESIGNswitchTESTINGswitchACCOUNTSSERVER + switch
  1. Server: ACCOUNTS block, because it has the most computers (180).
  2. Layout: star from ACCOUNTS to RESEARCH (130 m), DESIGN (50 m), TESTING (40 m).
  3. Repeater: between ACCOUNTS and RESEARCH (130 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): Optical fibre.
E2.29Practice5 marks

National Commerce College, Jaipur. It has four blocks, as shown in the layout.

Layout of the blocks

165 m50 m95 m165 m90 m140 mARTS210 computersCOMMERCE65 computersSCIENCE220 computersADMIN120 computers

Number of computers

BlockComputers
ARTS210
COMMERCE65
SCIENCE220
ADMIN120

Distance between blocks

FromToDistance
ARTSCOMMERCE165 m
ARTSSCIENCE95 m
ARTSADMIN90 m
COMMERCESCIENCE140 m
COMMERCEADMIN165 m
SCIENCEADMIN50 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for sending large files to the branch office.
Answer

Cable layout (star). R marks a repeater.

95 m140 mR50 mARTSswitchCOMMERCEswitchSCIENCESERVER + switchADMINswitch
  1. Server: SCIENCE block, because it has the most computers (220).
  2. Layout: star from SCIENCE to ARTS (95 m), COMMERCE (140 m), ADMIN (50 m).
  3. Repeater: between SCIENCE and COMMERCE (140 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): FTP (File Transfer Protocol).
E2.30Practice5 marks

FreshCart Retail, Lucknow. It has four blocks, as shown in the layout.

Layout of the blocks

105 m110 m120 m140 m50 m155 mBILLING120 computersCUSTOMER CARE75 computersWAREHOUSE45 computersIT70 computers

Number of computers

BlockComputers
BILLING120
CUSTOMER CARE75
WAREHOUSE45
IT70

Distance between blocks

FromToDistance
BILLINGCUSTOMER CARE105 m
BILLINGWAREHOUSE120 m
BILLINGIT50 m
CUSTOMER CAREWAREHOUSE155 m
CUSTOMER CAREIT140 m
WAREHOUSEIT110 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The type of network formed inside the campus.
Answer

Cable layout (star). R marks a repeater.

105 mR120 mR50 mBILLINGSERVER + switchCUSTOMER CAREswitchWAREHOUSEswitchITswitch
  1. Server: BILLING block, because it has the most computers (120).
  2. Layout: star from BILLING to CUSTOMER CARE (105 m), WAREHOUSE (120 m), IT (50 m).
  3. Repeater: between BILLING and CUSTOMER CARE (105 m) and between BILLING and WAREHOUSE (120 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): LAN (Local Area Network).
E2.31Practice5 marks

Gyan Deep School, Raipur. It has four blocks, as shown in the layout.

Layout of the blocks

65 m115 m175 m130 m160 m110 mADMIN55 computersLIBRARY170 computersSCIENCE35 computersHOSTEL135 computers

Number of computers

BlockComputers
ADMIN55
LIBRARY170
SCIENCE35
HOSTEL135

Distance between blocks

FromToDistance
ADMINLIBRARY65 m
ADMINSCIENCE175 m
ADMINHOSTEL160 m
LIBRARYSCIENCE110 m
LIBRARYHOSTEL130 m
SCIENCEHOSTEL115 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for logging in to a campus computer from another city.
Answer

Cable layout (star). R marks a repeater.

65 m110 mR130 mRADMINswitchLIBRARYSERVER + switchSCIENCEswitchHOSTELswitch
  1. Server: LIBRARY block, because it has the most computers (170).
  2. Layout: star from LIBRARY to ADMIN (65 m), SCIENCE (110 m), HOSTEL (130 m).
  3. Repeater: between LIBRARY and SCIENCE (110 m) and between LIBRARY and HOSTEL (130 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): TELNET (remote login).
E2.32Practice5 marks

Coastal Foods, Visakhapatnam. It has four blocks, as shown in the layout.

Layout of the blocks

75 m65 m170 m40 m110 m180 mHR80 computersSALES240 computersPRODUCTION195 computersSTORE220 computers

Number of computers

BlockComputers
HR80
SALES240
PRODUCTION195
STORE220

Distance between blocks

FromToDistance
HRSALES75 m
HRPRODUCTION170 m
HRSTORE110 m
SALESPRODUCTION180 m
SALESSTORE40 m
PRODUCTIONSTORE65 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The type of network formed between this campus and its branch in another city.
Answer

Cable layout (star). R marks a repeater.

75 m180 mR40 mHRswitchSALESSERVER + switchPRODUCTIONswitchSTOREswitch
  1. Server: SALES block, because it has the most computers (240).
  2. Layout: star from SALES to HR (75 m), PRODUCTION (180 m), STORE (40 m).
  3. Repeater: between SALES and PRODUCTION (180 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): WAN (Wide Area Network).
E2.33Practice5 marks

Care Plus Hospital, Ahmedabad. It has four blocks, as shown in the layout.

Layout of the blocks

155 m145 m30 m90 m165 m55 mOPD80 computersLAB195 computersWARD230 computersPHARMACY160 computers

Number of computers

BlockComputers
OPD80
LAB195
WARD230
PHARMACY160

Distance between blocks

FromToDistance
OPDLAB155 m
OPDWARD30 m
OPDPHARMACY165 m
LABWARD55 m
LABPHARMACY90 m
WARDPHARMACY145 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for video conferencing with the branch office.
Answer

Cable layout (star). R marks a repeater.

30 m55 m145 mROPDswitchLABswitchWARDSERVER + switchPHARMACYswitch
  1. Server: WARD block, because it has the most computers (230).
  2. Layout: star from WARD to OPD (30 m), LAB (55 m), PHARMACY (145 m).
  3. Repeater: between WARD and PHARMACY (145 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): VoIP (Voice over Internet Protocol).
E2.34Practice5 marks

Future Minds Institute, Chennai. It has four blocks, as shown in the layout.

Layout of the blocks

120 m35 m60 m70 m70 m40 mRECEPTION135 computersTRAINING220 computersDATA CENTRE65 computersCANTEEN195 computers

Number of computers

BlockComputers
RECEPTION135
TRAINING220
DATA CENTRE65
CANTEEN195

Distance between blocks

FromToDistance
RECEPTIONTRAINING120 m
RECEPTIONDATA CENTRE60 m
RECEPTIONCANTEEN70 m
TRAININGDATA CENTRE40 m
TRAININGCANTEEN70 m
DATA CENTRECANTEEN35 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The hardware or software that protects the network from unauthorised access.
Answer

Cable layout (star). R marks a repeater.

120 mR40 m70 mRECEPTIONswitchTRAININGSERVER + switchDATA CENTREswitchCANTEENswitch
  1. Server: TRAINING block, because it has the most computers (220).
  2. Layout: star from TRAINING to RECEPTION (120 m), DATA CENTRE (40 m), CANTEEN (70 m).
  3. Repeater: between TRAINING and RECEPTION (120 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): Firewall.
E2.35Practice5 marks

Shakti Tools, Ludhiana. It has four blocks, as shown in the layout.

Layout of the blocks

70 m50 m95 m75 m130 m105 mMAIN150 computersANNEXE60 computersWORKSHOP205 computersGUEST HOUSE100 computers

Number of computers

BlockComputers
MAIN150
ANNEXE60
WORKSHOP205
GUEST HOUSE100

Distance between blocks

FromToDistance
MAINANNEXE70 m
MAINWORKSHOP95 m
MAINGUEST HOUSE130 m
ANNEXEWORKSHOP105 m
ANNEXEGUEST HOUSE75 m
WORKSHOPGUEST HOUSE50 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The fastest wired medium to connect the blocks.
Answer

Cable layout (star). R marks a repeater.

95 m105 mR50 mMAINswitchANNEXEswitchWORKSHOPSERVER + switchGUEST HOUSEswitch
  1. Server: WORKSHOP block, because it has the most computers (205).
  2. Layout: star from WORKSHOP to MAIN (95 m), ANNEXE (105 m), GUEST HOUSE (50 m).
  3. Repeater: between WORKSHOP and ANNEXE (105 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): Optical fibre.
E2.36Practice5 marks

Lok Samachar, Guwahati. It has four blocks, as shown in the layout.

Layout of the blocks

135 m170 m170 m35 m30 m35 mEDITORIAL65 computersPRINTING60 computersMARKETING225 computersDISPATCH215 computers

Number of computers

BlockComputers
EDITORIAL65
PRINTING60
MARKETING225
DISPATCH215

Distance between blocks

FromToDistance
EDITORIALPRINTING135 m
EDITORIALMARKETING170 m
EDITORIALDISPATCH30 m
PRINTINGMARKETING35 m
PRINTINGDISPATCH35 m
MARKETINGDISPATCH170 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for sending large files to the branch office.
Answer

Cable layout (star). R marks a repeater.

170 mR35 m170 mREDITORIALswitchPRINTINGswitchMARKETINGSERVER + switchDISPATCHswitch
  1. Server: MARKETING block, because it has the most computers (225).
  2. Layout: star from MARKETING to EDITORIAL (170 m), PRINTING (35 m), DISPATCH (170 m).
  3. Repeater: between MARKETING and EDITORIAL (170 m) and between MARKETING and DISPATCH (170 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): FTP (File Transfer Protocol).
E2.37Practice5 marks

Seven Hills School, Shimla. It has four blocks, as shown in the layout.

Layout of the blocks

55 m125 m130 m140 m105 m85 mJUNIOR180 computersSENIOR60 computersSPORTS95 computersOFFICE170 computers

Number of computers

BlockComputers
JUNIOR180
SENIOR60
SPORTS95
OFFICE170

Distance between blocks

FromToDistance
JUNIORSENIOR55 m
JUNIORSPORTS130 m
JUNIOROFFICE105 m
SENIORSPORTS85 m
SENIOROFFICE140 m
SPORTSOFFICE125 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The type of network formed inside the campus.
Answer

Cable layout (star). R marks a repeater.

55 m130 mR105 mRJUNIORSERVER + switchSENIORswitchSPORTSswitchOFFICEswitch
  1. Server: JUNIOR block, because it has the most computers (180).
  2. Layout: star from JUNIOR to SENIOR (55 m), SPORTS (130 m), OFFICE (105 m).
  3. Repeater: between JUNIOR and SPORTS (130 m) and between JUNIOR and OFFICE (105 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): LAN (Local Area Network).
E2.38Practice5 marks

Nimbus Software, Kolkata. It has four blocks, as shown in the layout.

Layout of the blocks

55 m140 m165 m135 m75 m150 mRESEARCH75 computersDESIGN115 computersTESTING220 computersACCOUNTS250 computers

Number of computers

BlockComputers
RESEARCH75
DESIGN115
TESTING220
ACCOUNTS250

Distance between blocks

FromToDistance
RESEARCHDESIGN55 m
RESEARCHTESTING165 m
RESEARCHACCOUNTS75 m
DESIGNTESTING150 m
DESIGNACCOUNTS135 m
TESTINGACCOUNTS140 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for logging in to a campus computer from another city.
Answer

Cable layout (star). R marks a repeater.

75 m135 mR140 mRRESEARCHswitchDESIGNswitchTESTINGswitchACCOUNTSSERVER + switch
  1. Server: ACCOUNTS block, because it has the most computers (250).
  2. Layout: star from ACCOUNTS to RESEARCH (75 m), DESIGN (135 m), TESTING (140 m).
  3. Repeater: between ACCOUNTS and DESIGN (135 m) and between ACCOUNTS and TESTING (140 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): TELNET (remote login).
E2.39Practice5 marks

Triveni College, Prayagraj. It has four blocks, as shown in the layout.

Layout of the blocks

95 m125 m150 m180 m110 m60 mARTS25 computersCOMMERCE120 computersSCIENCE245 computersADMIN65 computers

Number of computers

BlockComputers
ARTS25
COMMERCE120
SCIENCE245
ADMIN65

Distance between blocks

FromToDistance
ARTSCOMMERCE95 m
ARTSSCIENCE150 m
ARTSADMIN110 m
COMMERCESCIENCE60 m
COMMERCEADMIN180 m
SCIENCEADMIN125 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The type of network formed between this campus and its branch in another city.
Answer

Cable layout (star). R marks a repeater.

150 mR60 m125 mRARTSswitchCOMMERCEswitchSCIENCESERVER + switchADMINswitch
  1. Server: SCIENCE block, because it has the most computers (245).
  2. Layout: star from SCIENCE to ARTS (150 m), COMMERCE (60 m), ADMIN (125 m).
  3. Repeater: between SCIENCE and ARTS (150 m) and between SCIENCE and ADMIN (125 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): WAN (Wide Area Network).
E2.40Practice5 marks

MetroMart, Bhubaneswar. It has four blocks, as shown in the layout.

Layout of the blocks

105 m80 m100 m85 m70 m135 mBILLING160 computersCUSTOMER CARE215 computersWAREHOUSE145 computersIT125 computers

Number of computers

BlockComputers
BILLING160
CUSTOMER CARE215
WAREHOUSE145
IT125

Distance between blocks

FromToDistance
BILLINGCUSTOMER CARE105 m
BILLINGWAREHOUSE100 m
BILLINGIT70 m
CUSTOMER CAREWAREHOUSE135 m
CUSTOMER CAREIT85 m
WAREHOUSEIT80 m

Suggest:

  1. The block for the server
  2. The cable layout
  3. The place for a repeater
  4. The device to be installed in every block
  5. The protocol for video conferencing with the branch office.
Answer

Cable layout (star). R marks a repeater.

105 mR135 mR85 mBILLINGswitchCUSTOMER CARESERVER + switchWAREHOUSEswitchITswitch
  1. Server: CUSTOMER CARE block, because it has the most computers (215).
  2. Layout: star from CUSTOMER CARE to BILLING (105 m), WAREHOUSE (135 m), IT (85 m).
  3. Repeater: between CUSTOMER CARE and BILLING (105 m) and between CUSTOMER CARE and WAREHOUSE (135 m), because the link is longer than 100 m.
  4. Device in every block: switch.
  5. Answer to (v): VoIP (Voice over Internet Protocol).
9

Flashcards for one-mark questions

Tap an option to check your answer at once; your score is saved

Quick quiz: 10 MCQs

Ten multiple-choice questions picked at random. Tap an option to answer. You get your score at the end.

10

Practice question papers

Twenty ready papers with blueprints and a random paper maker, all on the design of the CBSE Sample Question Paper 2026-27

Twenty ready practice papers

Each paper has 37 questions for 70 marks in Sections A to E, with internal choices (OR) in Q22, Q24, Q25 and Q27 to Q31. Unit marks are kept as in the syllabus: Python 40, Networks 10, Database 20. Every paper opens with its chapter-wise blueprint. Papers 11 to 20 are made of 450 questions that are not used in Papers 1 to 10 and are not repeated among themselves. Papers 1 to 10 use 419 different questions; 31 of their one-mark questions come in more than one paper.

Or make a fresh random paper

Marking scheme, download and timer

Blueprint only:
03:00:00

Choose Paper 1 to Paper 20, or make a random paper. The blueprint and the paper open here.

11

Last-day checklist

Read this the evening before and again at the exam centre gate

Before the paper

  • Write each template once from memory: stack, text file, CSV, binary, MySQL.
  • Revise the device table, protocol full forms and the six case-study rules.
  • Revise the six SQL "difference" pairs.

In the first 15 minutes

  • Mark Q27 to Q30 and Q32 to Q37. These are your template questions.
  • Where a question has OR, choose the part you know. Attempt only one.
  • Note the exact file name, function name and message given.

While writing

  • Start with Q37 and the SQL questions, then file handling, then Section A.
  • Keep indentation neat. Wrong indentation is a wrong program.
  • In error-correction questions, rewrite the full code and underline each correction.
Common mistake
  • Forgetting import pickle, import csv or import mysql.connector
  • Forgetting commit() after INSERT, UPDATE, DELETE
  • Opening a file to read with "w" (it erases the file)
  • Writing = NULL in place of IS NULL
  • Leaving a 4 or 5 mark question blank