Which of the following data types in Python is mutable?
(d) List A list can be changed in place. The other three cannot.
Minimum Learning Support Material · CBSE 2026-27
Notes · Code templates · 1131 solved questions · Flashcards · Quiz · Practice Paper Maker
Same design in the CBSE Sample Paper 2026-27 as in the 2025 and 2026 board papers
| Section | Questions | Marks each | Total | What comes |
|---|---|---|---|---|
| A | Q1 to Q21 | 1 | 21 | MCQ, True/False, output, full forms. Q20 and Q21 are Assertion-Reason. |
| B | Q22 to Q28 | 2 | 14 | Short theory, built-in functions, error correction, SQL commands, network terms |
| C | Q29 to Q31 | 3 | 9 | Text file, Stack, output or function writing |
| D | Q32 to Q35 | 4 | 16 | SQL queries, CSV file, two-table SQL, Python-MySQL |
| E | Q36, Q37 | 5 | 10 | Binary file, Networking case study |
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.
A suggested order of study for a student starting late. Pass mark is 33%, about 23 of 70 in theory.
import, opening the file, the loop and closing the file. Never leave a programming question blank.Unit 1 · feeds most of Section A and Section B
A token is the smallest meaningful unit of a program. Python has five kinds of tokens.
| Token | Meaning | Examples |
|---|---|---|
| Keyword | A reserved word with a fixed meaning | if else for while def return import True None break |
| Identifier | A name given by the programmer to a variable or function | marks roll_no Total2 |
| Literal | A fixed value written in the program | 25 3.14 "KV" True |
| Operator | A symbol that calculates or compares | + - * / // % ** == != > < and or not in is |
| Punctuator | A symbol that organises the code | ( ) [ ] { } : , . # |
Marks is not marks.Valid: roll_no _x Total2 Break
Invalid: 2total roll-no my name for
| Type | Holds | Example |
|---|---|---|
| int | whole numbers | 25 -7 |
| float | numbers with a decimal point | 3.14 74.0 |
| bool | truth values | True False |
| str | text inside quotes | "KV" 'XII' |
| list | many values, can be changed | [10, "a", 2.5] |
| tuple | many values, cannot be changed | (10, 20) and (5,) for one value |
| dict | key : value pairs | {"RNo": 12, "Name": "Asha"} |
| None | no value | None |
Python changes the type by itself, without loss of data.
5 + 2.5 gives 7.5 (int becomes float).
The programmer changes the type with a function.
int("25") → 25 · float(7) → 7.0 · str(25) → "25" · list("abc") → ['a', 'b', 'c']
| Error | What happens | Example |
|---|---|---|
| Syntax error | A 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 error | The program runs fully but the answer is wrong. | writing a + b where a * b was needed |
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(5) → 0, 1, 2, 3, 4 (stop is not included)range(2, 6) → 2, 3, 4, 5range(10, 0, -2) → 10, 8, 6, 4, 2An 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.
In daily life: At a traffic signal: if the light is green, go; else if it is yellow, slow down; else stop.
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.
In daily life: The school bell rings for every period: the same action repeats until the periods are over.
| Feature | String | List | Tuple | Dictionary |
|---|---|---|---|---|
| Written in | " " | [ ] | ( ) | { } |
| Can be changed? | No | Yes | No | Yes |
| Reached by | index | index | index | key |
| Example | "KVS" | [1, 2, 3] | (1, 2, 3) | {"a": 1} |
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]
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.
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}
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).
** works right to left: 2**3**2 = 2**9 = 512. / always gives float, // of two ints gives int.14 % 3 ** 2 * 4 → 14 % 9 = 5, then 5 * 4 = 2025 + 100**1**3 / 5 → 100 / 5 = 20.0, answer 45.0list dict set
A list passed to a function can be changed by the function.
int float bool str tuple
t[0] = 5 on a tuple or string gives TypeError. tuple + list also gives TypeError.
L = [1, 2, 3]
L.append(4)
Same object, now longer. So a list is mutable.
s = "KV"
s = s + "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).
s = "PYTHON"
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) → peDL[::-1] reverses any list or string.Leave a box empty to use the default. Coloured cells are picked; the small number shows the order.
| Type | Method | Result |
|---|---|---|
| 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 | |
| List | L.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 | |
| Dictionary | D.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 |
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.
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
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
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
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
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]
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 function | Where it comes from | Examples |
|---|---|---|
| Built-in | always available in Python | print() len() int() max() sorted() |
| Module function | available after import | math.sqrt() random.randint() statistics.mean() |
| User-defined | written by the programmer with def | def area(l, b): |
def name(parameters): ends with a colon.name(arguments). A function does nothing until it is called.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
return returns None.global statement, then reading it first, gives UnboundLocalError. The sample paper asks exactly this.A function is like a small machine. You give it inputs (arguments), it does its work, and it gives back a result with return.
In daily life: A juice machine: put in fruit (arguments), the machine works (function body), and juice comes out (return value).
The place where a variable can be used is called its scope.
In daily life: The school rules apply to every class (global). A rule made by one class teacher applies only inside that classroom (local).
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
| Error | When |
|---|---|
| ZeroDivisionError | divide by 0 |
| ValueError | int("abc"), "abc".index("z") |
| TypeError | 5 + "5", tuple + list |
| IndexError | index outside list |
| KeyError | missing dictionary key |
| NameError | variable not defined |
| EOFError | pickle.load() at end of file |
Risky statements are kept in try. If an error comes, Python does not crash; it jumps to except.
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.
| Function | Gives |
|---|---|
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.
| Call | Result | Meaning |
|---|---|---|
math.sqrt(16) | 4.0 | square root |
math.ceil(4.2) | 5 | next whole number above |
math.floor(4.8) | 4 | whole number below |
math.pow(2, 3) | 8.0 | power, answer in float |
math.fabs(-5) | 5.0 | positive value in float |
statistics.mean([2, 4, 9]) | 5 | average |
statistics.median([2, 4, 9]) | 4 | middle value |
statistics.mode([1, 2, 2]) | 2 | most frequent value |
Write import math, import statistics or import random at the top of the program before using these.
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.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
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.
The full address starting from the drive.
C:\School\XII\notes.txt
The address starting from the current folder.
notes.txt or data\notes.txt
| Mode | Meaning | File missing? | Old data |
|---|---|---|---|
| r / rb | read only | Error | safe |
| w / wb | write only | creates | erased |
| a / ab | append at end | creates | safe |
| r+ / rb+ | read and write | Error | safe |
| w+ / wb+ | write and read | creates | erased |
read() readline() readlines() write()pickle.dump() writes, pickle.load() readscsv.writer and csv.readerf.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.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.
In daily life: Writing homework in a notebook instead of only remembering it. The notebook is the file.
Hello class Python is easyText file: plain characters. Anyone can read it.
RNo,Name,Marks 1,Asha,91 2,Ravi,78CSV file: text in rows, values separated by commas. Opens in Excel.
€♦•]q (K☺X♦ Asha K[ e.Binary file: bytes written by pickle. Fast for Python, not readable by us.
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
2. After f.read(5): five characters are read, f.tell() is 5
3. After f.seek(0): the pointer is back at the start
In daily life: A bookmark in a book: it remembers where you stopped, and you can move it to any page.
In daily life: Reading a notebook (r), taking a fresh notebook (w), and writing on the next empty line of the same notebook (a).
| Method | What it does | Gives back |
|---|---|---|
f.read() | reads the whole file | one string |
f.read(n) | reads the next n characters | one string |
f.readline() | reads one line, including its \n | one string |
f.readlines() | reads all the lines | a list of strings |
f.write(s) | writes the string s; add \n yourself for a new line | number of characters written |
f.writelines(L) | writes all the strings of list L; no \n is added | nothing |
The file has three lines: Hello, World, Bye
f.read()'Hello\nWorld\nBye\n'everything, as one string
f.readline()'Hello\n'only one line
f.readlines()['Hello\n', 'World\n', 'Bye\n']all lines, as a list
In these examples the file a.txt has three lines: Hello, World, Bye.
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'
| Point | Text file | Binary file | CSV file |
|---|---|---|---|
| Stores | readable characters, lines end with EOL | bytes, same as in memory; not readable | text rows, values separated by commas |
| Extension | .txt | .dat | .csv |
| Module | none | pickle | csv |
| Read | read() readline() readlines() | pickle.load(f) | csv.reader(f) |
| Write | write() writelines() | pickle.dump(obj, f) | writerow() one row, writerows() many rows |
| Modes | r, w, a | rb, wb, ab | r, w, a with newline="" |
dump() does it. Unpickling is the reverse; load() does it.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).
In daily life: Packing clothes into a suitcase for a journey (dump) and unpacking them at home (load).
# 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 show | Condition to write |
|---|---|
| digits in the file | if ch.isdigit(): |
| vowels / capital letters | if ch in "aeiouAEIOU": / if ch.isupper(): |
| words starting with a letter | if w[0] in "Aa": or w.startswith("A") |
| words of length 4 or more | if len(w) >= 4: |
| lines starting with 'T' | if line[0] == "T": |
| number of lines | len(f.readlines()) |
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()
int() or float() before comparing or adding. Write newline="" while opening for writing.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()
try → while True → pickle.load(f) → except EOFError. Learn this skeleton by heart.wb mode.wb mode.Q30 · 3 marks every year
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
stk = []emptypush 10push 20push 30poppopThe 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.
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.
| Term | Meaning |
|---|---|
| Push | add an item at the top |
| Pop | remove the item at the top |
| Peek / Top | see the top item without removing it |
| Underflow | trying to pop from an empty stack |
| Overflow | trying to push into a full stack |
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.
| Term | Meaning |
|---|---|
| Sender | the device that sends the data |
| Receiver | the device that gets the data |
| Message | the data being sent: text, picture, sound, video |
| Communication medium | the path between sender and receiver: cable or wireless |
| Protocol | the set of rules both sides follow |
| Bandwidth | the range of frequencies a channel can carry; measured in Hz, kHz, MHz |
| Data transfer rate | amount of data sent in one second; measured in bps, Kbps, Mbps, Gbps |
| IP address | the 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 address | the 48-bit physical address fixed on the network card by the maker, e.g. 00:1A:2B:3C:4D:5E. It does not change. |
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).
| Device | One-line job |
|---|---|
| Modem | Converts digital to analog and back (modulation, demodulation) |
| RJ45 | Registered Jack 45, the connector on Ethernet cable |
| Ethernet card (NIC) | Connects a computer to the network; carries a unique MAC address |
| Wi-Fi card | Connects a computer to a wireless network without a cable |
| Repeater | Regenerates a weak signal on long cable runs |
| Hub | Sends data to all connected devices |
| Switch | Sends data only to the destination device; use inside each building |
| Router | Connects different networks and chooses the path |
| Gateway | Entry and exit point of a network; joins networks with different protocols |
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.
| Topology | Advantage | Disadvantage |
|---|---|---|
| Bus | Simple, least cable, cheap | Backbone cable fails, whole network stops; fault hard to find |
| Star | One cable fails, only that node stops; easy to add nodes | Central device fails, network stops; more cable |
| Tree | Hierarchical, easy to expand (bus + star) | Backbone fails, the branches below it stop |
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.
| Short | Full form | Use |
|---|---|---|
| HTTP / HTTPS | HyperText Transfer Protocol (Secure) | web pages |
| FTP | File Transfer Protocol | upload and download files |
| SMTP | Simple Mail Transfer Protocol | sending e-mail |
| POP3 | Post Office Protocol version 3 | receiving e-mail |
| TCP/IP | Transmission Control Protocol / Internet Protocol | base of the Internet |
| PPP | Point-to-Point Protocol | direct link between two devices |
| TELNET | Teletype Network | remote login |
| VoIP | Voice over Internet Protocol | voice and video calls over Internet |
| URL | Uniform Resource Locator | address of a web resource |
| XML / HTML | eXtensible / HyperText Markup Language | XML carries data (own tags), HTML displays it (fixed tags) |
| ARPANET | Advanced Research Projects Agency Network | first network, ancestor of the Internet |
| MAC / NIC | Media Access Control / Network Interface Card | physical address / network card |
| Term | Meaning |
|---|---|
| WWW | World Wide Web: the collection of linked web pages opened through the Internet. It is one service of the Internet, not the Internet itself. |
| Web page | one document written in HTML |
| Website | a group of related web pages under one domain name |
| Web browser | software that opens web pages: Chrome, Firefox, Edge |
| Web server | the computer or program that stores websites and sends pages to browsers |
| Web hosting | the service of keeping a website on a web server so that everyone can open it |
| Domain name | the easy name of a website that stands for its IP address: cbse.gov.in |
| URL | the complete address of one resource on the web |
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.
Type the block names, number of computers and distances from any question. The data of CBSE 2026 is filled in.
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.
| RNo | Name | Marks |
|---|---|---|
| 1 | Asha | 91 |
| 2 | Ravi | 78 |
| 3 | Tina | 85 |
| Relation STUDENT: 3 columns → degree 3; 3 rows → cardinality 3 | ||
| Term | Meaning |
|---|---|
| Relation | table |
| Tuple | row / record |
| Attribute | column / field |
| Degree | number of columns |
| Cardinality | number of rows |
| Domain | set of allowed values of a column |
| RNo | Name | City | Marks |
|---|---|---|---|
| 1 | Asha | Delhi | 91 |
| 2 | Ravi | Agra | 78 |
| 3 | Tina | Delhi | 85 |
In daily life: The attendance register of a class: every student is one row, and every heading (Roll No, Name) is one column.
In daily life: Your admission number is your primary key in school: no two students share it, and it is never blank.
| Data type | Stores | Example |
|---|---|---|
| INT | whole numbers | 25 |
| FLOAT | numbers with decimals | 91.5 |
| DECIMAL(7,2) | 7 digits in all, 2 after the point | 99999.99 |
| CHAR(n) | text of fixed length n | 'XII' |
| VARCHAR(n) | text of any length up to n | 'Asha' |
| DATE | date as 'YYYY-MM-DD' | '2027-03-15' |
| Constraint | Rule it puts on a column |
|---|---|
| NOT NULL | the column cannot be left empty |
| UNIQUE | no two rows can have the same value |
| PRIMARY KEY | unique and not null; only one in a table |
CREATE ALTER DROP
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;
CREATEALTERDROP
Makes, changes or removes the table itself.
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.
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;
SELECT city, COUNT(*) FROM student WHERE marks > 60 GROUP BY city HAVING COUNT(*) > 1;
FROM studentTake the whole table.
| name | city | marks |
|---|---|---|
| Asha | Delhi | 91 |
| Ravi | Agra | 55 |
| Tina | Delhi | 78 |
| Om | Agra | 82 |
| Zoya | Pune | 67 |
WHERE marks > 60Keep only the rows that pass the condition. Ravi (55) goes out.
| name | city | marks |
|---|---|---|
| Asha | Delhi | 91 |
| Tina | Delhi | 78 |
| Om | Agra | 82 |
| Zoya | Pune | 67 |
GROUP BY cityPut the rows of the same city together.
| city | rows in the group |
|---|---|
| Delhi | Asha, Tina |
| Agra | Om |
| Pune | Zoya |
HAVING COUNT(*) > 1Keep only the groups that pass the condition.
| city | rows in the group |
|---|---|
| Delhi | Asha, Tina |
SELECT city, COUNT(*)Show the asked columns. This is the output.
| city | COUNT(*) |
|---|---|
| Delhi | 2 |
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.
| LIKE pattern | Matches |
|---|---|
'A%' | starts with A |
'%a' | ends with a |
'%an%' | contains "an" anywhere |
'_a%' | second letter is a |
'____' | exactly four characters |
SELECT name AS Student, marks*2 AS Double_Marks FROM student;% stands for any number of characters, _ stands for exactly one character. MySQL ignores capital and small letters while matching.
| STUDENT | FEE | ||
|---|---|---|---|
| rno | name | rno | amount |
| 1 | Asha | 1 | 5000 |
| 2 | Ravi | 2 | 4500 |
| Join | Rows | Columns |
|---|---|---|
| Cartesian product: every row with every row | 2 x 2 = 4 | 2 + 2 = 4 |
| Equi join: only rows where rno matches | 2 | 4 (rno twice) |
| Natural join: matching rows, common column once | 2 | 3 |
In daily life: Matching the fee receipts with the class list: a receipt is joined to the student who has the same roll number.
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)
| rno | name | city | marks | fee |
|---|---|---|---|---|
| 1 | Asha | Delhi | 91 | 5000 |
| 2 | Ravi | Agra | 55 | 4500 |
| 3 | Tina | Delhi | 78 | NULL |
| 4 | Om | Agra | 82 | 5000 |
| 5 | Zoya | Pune | 67 | 4000 |
SUM(column)adds the values of a column; NULL is skippedSELECT 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 skippedSELECT 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 valueSELECT MAX(marks) FROM student;
| MAX(marks) |
|---|
| 91 |
SELECT MAX(name) FROM student;
| MAX(name) |
|---|
| Zoya |
SELECT city, MAX(marks) FROM student GROUP BY city;
| city | MAX(marks) |
|---|---|
| Agra | 82 |
| Delhi | 91 |
| Pune | 67 |
MIN(column)the smallest valueSELECT 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 NULLSELECT COUNT(*) FROM student;
| COUNT(*) |
|---|
| 5 |
SELECT COUNT(fee) FROM student;
| COUNT(fee) |
|---|
| 4 |
SELECT COUNT(DISTINCT city) FROM student;
| COUNT(DISTINCT city) |
|---|
| 3 |
WHEREkeeps only the rows that pass the conditionSELECT name, marks FROM student WHERE marks > 80;
| name | marks |
|---|---|
| Asha | 91 |
| Om | 82 |
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 onceSELECT 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 includedSELECT name, marks FROM student WHERE marks BETWEEN 60 AND 80;
| name | marks |
|---|---|
| Tina | 78 |
| Zoya | 67 |
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 listSELECT 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 oneSELECT 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 missingSELECT 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 writtenSELECT name, marks FROM student ORDER BY marks;
| name | marks |
|---|---|
| Ravi | 55 |
| Zoya | 67 |
| Tina | 78 |
| Om | 82 |
| Asha | 91 |
SELECT name, marks FROM student ORDER BY marks DESC;
| name | marks |
|---|---|
| Asha | 91 |
| Om | 82 |
| Tina | 78 |
| Zoya | 67 |
| Ravi | 55 |
SELECT city, name FROM student ORDER BY city, name;
| city | name |
|---|---|
| Agra | Om |
| Agra | Ravi |
| Delhi | Asha |
| Delhi | Tina |
| Pune | Zoya |
GROUP BYmakes one group for every different valueSELECT city, COUNT(*) FROM student GROUP BY city;
| city | COUNT(*) |
|---|---|
| Agra | 2 |
| Delhi | 2 |
| Pune | 1 |
SELECT city, MAX(marks) FROM student GROUP BY city;
| city | MAX(marks) |
|---|---|
| Agra | 82 |
| Delhi | 91 |
| Pune | 67 |
SELECT city, SUM(fee) FROM student GROUP BY city;
| city | SUM(fee) |
|---|---|
| Agra | 9500 |
| Delhi | 5000 |
| Pune | 4000 |
HAVINGkeeps only the groups that pass the conditionSELECT city, COUNT(*) FROM student GROUP BY city HAVING COUNT(*) > 1;
| city | COUNT(*) |
|---|---|
| Agra | 2 |
| Delhi | 2 |
SELECT city, AVG(marks) FROM student GROUP BY city HAVING AVG(marks) > 70;
| city | AVG(marks) |
|---|---|
| Delhi | 84.5 |
SELECT city, MAX(marks) FROM student GROUP BY city HAVING MAX(marks) < 80;
| city | MAX(marks) |
|---|---|
| Pune | 67 |
INSERT INTOadds a new rowINSERT 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 conditionUPDATE 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 staysDELETE 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.
CREATE TABLEmakes a new tableCREATE 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 tableALTER 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 completelyDROP 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.
| Pair | First | Second |
|---|---|---|
| ALTER / UPDATE | DDL, changes table structure | DML, changes data in rows |
| DELETE / DROP | removes rows, table stays | removes the whole table |
| WHERE / HAVING | condition on rows, before grouping | condition on groups, used with GROUP BY |
| CHAR / VARCHAR | fixed length | variable length |
| PRIMARY KEY / UNIQUE | one per table, no NULL | many per table, NULL allowed |
| COUNT(*) / COUNT(col) | counts all rows | skips NULL in that column |
IS NULL, never = NULL. Put text and dates in quotes: '2024-12-31'. End every query with a semicolon.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).
import mysql.connectorconnect(host, user, password, database)cursor()execute("query")commit() for INSERT, UPDATE, DELETE · fetchall() for SELECTclose()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.
1131 questions in 20 types, arranged in the order of the CBSE Sample Paper 2026-27
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.
Which of the following data types in Python is mutable?
(d) List A list can be changed in place. The other three cannot.
t = (1, 2, 3) and l = [4, 5]. What happens on print(t + l)?
(c) Error, because a tuple cannot be joined with a list + needs both operands of the same sequence type, so TypeError is raised.
Dl is a dictionary with keys 'Pen', 'Pencil', 'Scale', 'InkPen' and number values. print(12 in Dl) shows ...
(a) False in checks the keys of a dictionary, not the values.
What is the data type of the result of 5 // 2?
(b) int Floor division of two integers gives an integer (2).
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 ...
(c) Error Assigning to y makes it local, and it is read before it has a value: UnboundLocalError.
data(num) returns 190 / (29 - num). On ZeroDivisionError it writes "Num was 29" to errorlog.txt. What is in the file after data(29)?
(a) Num was 29 29 - 29 is 0, so the except block runs and writes the message.
State True or False: In Python, the data type of 74 is the same as the data type of 74.0.
(b) False 74 is int and 74.0 is float.
Which of the following statements is true about dictionaries in Python?
(b) A dictionary cannot have two elements with the same key Keys must be unique. Values can repeat.
State True or False: Logical errors can be handled with try-except-finally.
(b) False Only run-time errors (exceptions) can be handled.
Which file mode opens a binary .dat file only for reading?
(b) rb r = read, b = binary.
State True or False: A Python list must always contain all its elements of the same data type.
(b) False A list can mix types: [1, 'a', 2.5].
Which of the following is a valid identifier and not a keyword?
(b) Break Python is case-sensitive; only break is a keyword.
Which operator checks whether two names refer to the same object?
(a) is is compares identity; == compares values.
Which of the following print() calls is invalid?
(b) print("A", sep="*", 10) A positional argument (10) cannot come after a keyword argument (sep).
Which of the following is not a Python keyword?
(b) eval eval is a built-in function, not a keyword.
Which of the following is an invalid identifier?
(c) 1total An identifier cannot start with a digit.
The input() function always returns a value of type ...
(b) str Use int() or float() to convert the string.
Which of these operators has the highest precedence?
(c) ** Power is evaluated before multiplication and addition.
Which statement skips the rest of the current round of a loop and starts the next round?
(b) continue break leaves the loop; continue goes to the next round.
range(1, 10, 3) generates the numbers ...
(a) 1, 4, 7 Start 1, step 3, and the stop value 10 is not included.
A Python string is ...
(b) an immutable sequence Characters are indexed, but they cannot be changed in place.
Which of the following creates a tuple with one element?
(b) (5,) The comma makes it a tuple; (5) is just the integer 5.
Which list method adds one element at the end of a list?
(b) append() extend() adds many elements; insert() needs a position.
Which list method removes and returns the last element?
(b) pop() pop() without an index removes the last element.
The keys of a dictionary must be ...
(b) immutable int, float, str and tuple can be keys; a list cannot.
D.get(k) returns ______ when the key k is not in the dictionary.
(b) None D[k] would raise KeyError; get() does not.
Which keyword is used to define a function?
(b) def A function starts with def, e.g. def area(r):
A function that has no return statement returns ...
(b) None Without return, a function gives back None.
For def f(a, b=5, c=10): which call is invalid?
(c) f() a has no default value, so one argument is compulsory.
A variable created inside a function is called a ______ variable.
(b) local It exists only inside that function, so it is a local variable.
Which keyword lets a function change a global variable?
(a) global Writing global x inside the function makes assignments change the global x instead of creating a local one.
The values passed to a function in the function call are called ...
(b) arguments Parameters are the names in the function header.
Which block of exception handling always runs?
(d) finally finally runs whether or not an exception occurred, so it is used for clean-up such as closing files.
int("abc") raises ...
(b) ValueError The type is right (a string) but the value cannot be converted.
Reading L[10] from a list of 3 elements raises ...
(b) IndexError Valid indexes are 0 to 2 (or -1 to -3), so index 10 raises IndexError.
Using a variable that was never defined raises ...
(a) NameError Python cannot find the name, so NameError is raised.
Which method reads the whole text file as one string?
(a) read() read() returns all the text as one string; readline() gives one line and readlines() a list of lines.
readlines() returns ...
(b) a list of strings Each element is one line of the file.
Which mode opens a text file to add data at the end?
(c) a a = append.
Which module is used to read and write binary files of Python objects?
(b) pickle pickle.dump() writes an object to a binary file and pickle.load() reads it back.
pickle.load() raises ______ when no record is left in the file.
(a) EOFError EOF means End Of File.
Which method of a csv writer object writes one row?
(b) writerow() writerows() writes many rows.
f.seek(0) ...
(b) moves the file pointer to the beginning tell() returns the position.
A stack follows the ______ principle.
(b) LIFO Last In, First Out.
How many times will the body of the loop for i in range(0, 10, 2): run?
(d) 5 The values of i are 0, 2, 4, 6, 8.
How many times will the body of the loop for i in range(1, 10, 3): run?
(d) 3 The values of i are 1, 4, 7.
How many times will the body of the loop for i in range(5, 0, -1): run?
(b) 5 The values of i are 5, 4, 3, 2, 1.
How many times will the body of the loop for i in range(2, 20, 4): run?
(c) 5 The values of i are 2, 6, 10, 14, 18.
How many times will the body of the loop for i in range(10, 1, -3): run?
(a) 3 The values of i are 10, 7, 4.
How many times will the body of the loop for i in range(0, 7, 1): run?
(d) 7 The values of i are 0, 1, 2, 3, 4, 5, 6.
How many times will the body of the loop for i in range(3, 3, 1): run?
(b) 0 The start is not less than the stop, so the loop does not run.
How many times will the body of the loop for i in range(1, 16, 5): run?
(d) 3 The values of i are 1, 6, 11.
How many times will the body of the loop for i in range(20, 10, -2): run?
(c) 5 The values of i are 20, 18, 16, 14, 12.
How many times will the body of the loop for i in range(4, 25, 7): run?
(d) 3 The values of i are 4, 11, 18.
How many times will the body of the loop for i in range(0, 9, 4): run?
(d) 3 The values of i are 0, 4, 8.
How many times will the body of the loop for i in range(6, 0, -2): run?
(b) 3 The values of i are 6, 4, 2.
What is the data type of the value of 7 / 2?
(d) float The value is 3.5.
What is the data type of the value of "7" * 2?
(b) str The value is '77'.
What is the data type of the value of [1] + [2]?
(d) list The value is [1, 2].
What is the data type of the value of (1, 2) + (3,)?
(b) tuple The value is (1, 2, 3).
What is the data type of the value of 3 > 2?
(b) bool The value is True.
What is the data type of the value of {"a": 1}?
(b) dict The value is {'a': 1}.
What is the data type of the value of int("5") + 2.0?
(a) float The value is 7.0.
What is the data type of the value of "5" + "5"?
(c) str The value is '55'.
What is the data type of the value of len("abc")?
(c) int The value is 3.
What is the data type of the value of [1, 2][0:1]?
(d) list The value is [1].
What is the data type of the value of "abc"[0]?
(c) str The value is 'a'.
What is the data type of the value of 10 // 3?
(d) int The value is 3.
What is the value of the expression 7 + 3 * 2?
(c) 13 Precedence: ** first, then * / // % (left to right), then + -. Working: 3 * 2 = 6; 7 + 6 = 13.
What is the value of the expression (7 + 3) * 2?
(b) 20 Precedence: ** first, then * / // % (left to right), then + -. Working: 7 + 3 = 10; 10 * 2 = 20.
What is the value of the expression 2 ** 3 + 1?
(b) 9 Precedence: ** first, then * / // % (left to right), then + -. Working: 2 ** 3 = 8; 8 + 1 = 9.
What is the value of the expression 17 % 5 * 2?
(a) 4 Precedence: ** first, then * / // % (left to right), then + -. Working: 17 % 5 = 2; 2 * 2 = 4.
What is the value of the expression 9 // 2 + 9 % 2?
(b) 5 Precedence: ** first, then * / // % (left to right), then + -. Working: 9 // 2 = 4; 9 % 2 = 1; 4 + 1 = 5.
What is the value of the expression 10 - 4 // 2?
(d) 8 Precedence: ** first, then * / // % (left to right), then + -. Working: 4 // 2 = 2; 10 - 2 = 8.
What is the value of the expression 2 * 3 ** 2?
(b) 18 Precedence: ** first, then * / // % (left to right), then + -. Working: 3 ** 2 = 9; 2 * 9 = 18.
What is the value of the expression 15 // 4 * 4?
(a) 12 Precedence: ** first, then * / // % (left to right), then + -. Working: 15 // 4 = 3; 3 * 4 = 12.
What is the value of the expression len("CBSE") * 3?
(d) 12 Precedence: ** first, then * / // % (left to right), then + -. Working: len('CBSE') = 4; 4 * 3 = 12.
What is the value of the expression 20 - 3 * 4 + 2?
(b) 10 Precedence: ** first, then * / // % (left to right), then + -. Working: 3 * 4 = 12; 20 - 12 = 8; 8 + 2 = 10.
What is the value of the expression 8 % 3 ** 2?
(d) 8 Precedence: ** first, then * / // % (left to right), then + -. Working: 3 ** 2 = 9; 8 % 9 = 8.
What is the value of the expression 6 + 18 // 4?
(d) 10 Precedence: ** first, then * / // % (left to right), then + -. Working: 18 // 4 = 4; 6 + 4 = 10.
What is the value of the expression 5 * 2 ** 2 - 1?
(d) 19 Precedence: ** first, then * / // % (left to right), then + -. Working: 2 ** 2 = 4; 5 * 4 = 20; 20 - 1 = 19.
What is the value of the expression 100 // 7 % 4?
(c) 2 Precedence: ** first, then * / // % (left to right), then + -. Working: 100 // 7 = 14; 14 % 4 = 2.
Which error does the statement "abc" + 5 raise?
(c) TypeError A str and an int cannot be added with +, so TypeError.
Which error does the statement [1, 2, 3][5] raise?
(a) IndexError Index 5 does not exist in a list of 3 elements: IndexError.
Which error does the statement {"a": 1}["b"] raise?
(d) KeyError The key "b" is not in the dictionary: KeyError.
Which error does the statement int("x1") raise?
(c) ValueError "x1" is a string but not a valid number, so int() raises ValueError.
Which error does the statement print(xyz) raise? (xyz was never given a value.)
(c) NameError xyz has no value, so Python cannot find the name: NameError.
Which error does the statement 5 % 0 raise?
(d) ZeroDivisionError Taking a remainder by 0 is not possible: ZeroDivisionError.
Which error does the statement (1, 2)[3] raise?
(c) IndexError The tuple has indexes 0 and 1 only: IndexError.
Which error does the statement float("ten") raise?
(a) ValueError "ten" is not written in digits, so float() raises ValueError.
Which error does the statement [1, 2].remove(5) raise?
(a) ValueError remove() raises ValueError when the value is not in the list.
Which error does the statement len(5) raise?
(b) TypeError An int has no length, so len() raises TypeError.
A function is defined as def f(a, b=3): return a * b. What is the value of f(4)?
(c) 12 b takes its default value 3.
A function is defined as def f(a, b=3): return a * b. What is the value of f(4, 2)?
(b) 8 b takes the second value passed.
A function is defined as def f(a, b=10): return a + b. What is the value of f(5)?
(a) 15 b takes its default value 10.
A function is defined as def f(a, b=10): return a + b. What is the value of f(5, 1)?
(b) 6 b takes the second value passed.
A function is defined as def f(a, b=2): return a ** b. What is the value of f(3)?
(d) 9 b takes its default value 2.
A function is defined as def f(a, b=2): return a ** b. What is the value of f(2, 5)?
(b) 32 b takes the second value passed.
A function is defined as def f(a, b=4): return a - b. What is the value of f(9)?
(b) 5 b takes its default value 4.
A function is defined as def f(a, b=4): return a - b. What is the value of f(9, 9)?
(b) 0 b takes the second value passed.
A function is defined as def f(a, b=5): return a // b. What is the value of f(17)?
(d) 3 b takes its default value 5.
A function is defined as def f(a, b=5): return a // b. What is the value of f(17, 2)?
(c) 8 b takes the second value passed.
A function is defined as def f(a, b=3): return a % b. What is the value of f(10)?
(c) 1 b takes its default value 3.
A function is defined as def f(a, b=3): return a % b. What is the value of f(10, 4)?
(d) 2 b takes the second value passed.
What is the output of print("hello World".upper())?
(a) HELLO WORLD upper() changes every letter to capital.
What is the output of print("hello World".title())?
(b) Hello World title() makes the first letter of every word capital and the others small.
What is the output of print("pYTHON lab".capitalize())?
(d) Python lab capitalize() makes only the first character capital and all the other letters small.
What is the output of print("pYTHON lab".lower())?
(d) python lab lower() changes every letter to small.
What is the output of print("cbse BOARD exam".title())?
(c) Cbse Board Exam title() makes the first letter of every word capital.
What is the output of print("cbse BOARD exam".upper())?
(b) CBSE BOARD EXAM upper() changes every letter to capital.
What is the output of print("kV delhi".capitalize())?
(c) Kv delhi capitalize() makes only the first character of the whole string capital.
What is the output of print("kV delhi".title())?
(d) Kv Delhi title() makes the first letter of every word capital.
What is the output of print("gOOD luck".lower())?
(a) good luck lower() changes every letter to small.
What is the output of print("gOOD luck".capitalize())?
(d) Good luck capitalize() gives a capital first letter and makes all the other letters small.
Which statement opens "data.csv" so that new rows are added without erasing the old rows?
(a) open("data.csv", "a") a = append.
Which method of a csv writer object writes many rows in one call?
(b) writerows() writerow() writes one row; writerows() takes a list of rows and writes them all.
f = open("a.txt") opens the file in which mode?
(a) r Read mode is the default.
Which mode allows both reading and writing and does not erase the existing data?
(b) r+ r+ opens an existing file for reading and writing without erasing it; w+ would erase it.
A stack is stored in the list st. Which expression gives the top element without removing it?
(b) st[-1] The top of the stack is the last element, st[-1]; st.pop() would remove it.
Which operation is not allowed on a stack?
(c) Insert in the middle A stack works at one end only.
To write objects with pickle.dump(), the file should be opened in mode ...
(c) wb pickle writes bytes, so the file must be opened in binary write mode 'wb' (or 'ab').
How many values can a Python function return?
(c) One or more Many values are returned as a tuple.
What is the advantage of with open("a.txt") as f:?
(b) The file is closed automatically The with block closes the file automatically, even if an error occurs.
Which statement imports only the function sqrt from the math module?
(b) from math import sqrt from math import sqrt brings in only sqrt, which can then be used without writing math.
Write the output.
L1 = [10, 20, 25, 30] L1.insert(1, 15) print(L1)
[10, 15, 20, 25, 30]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L1 = [10, 20, 25, 30] | L1 = [10, 20, 25, 30] | |
| 2 | L1.insert(1, 15) | L1 = [10, 15, 20, 25, 30] | |
| 3 | print(L1) | [10, 15, 20, 25, 30]⏎ |
Write the output.
print("programming is amazing".split("m"))['progra', '', 'ing is a', 'azing']
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("programming is amazing".split("m")) | ['progra', '', 'ing is a', 'azing']⏎ |
Write the output.
print(25 + 100**1**3 / 5)
45.0
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(25 + 100**1**3 / 5) | 45.0⏎ |
Write the output.
text = "Drone Expo" print(text[-2::-4])
peD
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | text = "Drone Expo" | text = 'Drone Expo' | |
| 2 | print(text[-2::-4]) | peD⏎ |
Write the output.
print("the Truth".capitalize())The truth
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("the Truth".capitalize()) | The truth⏎ |
Write the output.
print("PythonProgram"[-1:2:-2])mroPo
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("PythonProgram"[-1:2:-2]) | mroPo⏎ |
Write the output.
print("War and Peace by Leo Tolstoy".partition("by"))('War and Peace ', 'by', ' Leo Tolstoy')Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("War and Peace by Leo Tolstoy".partition("by")) | ('War and Peace ', 'by', ' Leo Tolstoy')⏎ |
Write the output.
print(14 % 3 ** 2 * 4)
20
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(14 % 3 ** 2 * 4) | 20⏎ |
Write the output.
L = ['TIC', 'TAC'] print(L[::-1])
['TAC', 'TIC']
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = ['TIC', 'TAC'] | L = ['TIC', 'TAC'] | |
| 2 | print(L[::-1]) | ['TAC', 'TIC']⏎ |
Write the output.
print(2 ** 3 ** 2 // 5)
102
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(2 ** 3 ** 2 // 5) | 102⏎ |
Write the output.
print("CBSE-2027".isalnum(), "CBSE2027".isalnum())False True
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("CBSE-2027".isalnum(), "CBSE2027".isalnum()) | False True⏎ |
Write the output.
T = (5, 10, 15, 20) print(T[1:3] + T[-1:])
(10, 15, 20)
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | T = (5, 10, 15, 20) | T = (5, 10, 15, 20) | |
| 2 | print(T[1:3] + T[-1:]) | (10, 15, 20)⏎ |
Write the output.
print(not 5 > 3 or 4 == 4 and 7 < 2)
False
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(not 5 > 3 or 4 == 4 and 7 < 2) | False⏎ |
Write the output.
s = "Kendriya" print(s[1:6:2].upper())
EDI
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | s = "Kendriya" | s = 'Kendriya' | |
| 2 | print(s[1:6:2].upper()) | EDI⏎ |
Write the output.
print(17 // 5, 17 % 5)
3 2
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(17 // 5, 17 % 5) | 3 2⏎ |
Write the output.
print(2 + 3 * 4 ** 2)
50
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(2 + 3 * 4 ** 2) | 50⏎ |
Write the output.
print(10 / 4, 10 // 4)
2.5 2
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(10 / 4, 10 // 4) | 2.5 2⏎ |
Write the output.
print("KVS" * 2 + "!")KVSKVS!
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("KVS" * 2 + "!") | KVSKVS!⏎ |
Write the output.
print(len("Computer Science"))16
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(len("Computer Science")) | 16⏎ |
Write the output.
print("Python"[1:4])yth
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Python"[1:4]) | yth⏎ |
Write the output.
print("Python"[::-1])nohtyP
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Python"[::-1]) | nohtyP⏎ |
Write the output.
print("Informatics"[::3])Ioac
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Informatics"[::3]) | Ioac⏎ |
Write the output.
print("hello world".title())Hello World
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("hello world".title()) | Hello World⏎ |
Write the output.
print("Board Exam".swapcase())bOARD eXAM
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Board Exam".swapcase()) | bOARD eXAM⏎ |
Write the output.
print("banana".count("an"))2
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("banana".count("an")) | 2⏎ |
Write the output.
print("mississippi".find("ss"))2
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("mississippi".find("ss")) | 2⏎ |
Write the output.
print("a-b-c".split("-"))['a', 'b', 'c']
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("a-b-c".split("-")) | ['a', 'b', 'c']⏎ |
Write the output.
print(" ".join(["XII", "CS"]))XII CS
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(" ".join(["XII", "CS"])) | XII CS⏎ |
Write the output.
L = [3, 1, 2] L.sort(reverse=True) print(L)
[3, 2, 1]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [3, 1, 2] | L = [3, 1, 2] | |
| 2 | L.sort(reverse=True) | L = [3, 2, 1] | |
| 3 | print(L) | [3, 2, 1]⏎ |
Write the output.
L = [1, 2, 3] L.extend([4, 5]) print(len(L))
5
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [1, 2, 3] | L = [1, 2, 3] | |
| 2 | L.extend([4, 5]) | L = [1, 2, 3, 4, 5] | |
| 3 | print(len(L)) | 5⏎ |
Write the output.
L = [10, 20, 30, 40] print(L[1:3], L[-1])
[20, 30] 40
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [10, 20, 30, 40] | L = [10, 20, 30, 40] | |
| 2 | print(L[1:3], L[-1]) | [20, 30] 40⏎ |
Write the output.
L = [5, 8, 5, 2] L.remove(5) print(L)
[8, 5, 2]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [5, 8, 5, 2] | L = [5, 8, 5, 2] | |
| 2 | L.remove(5) | L = [8, 5, 2] | |
| 3 | print(L) | [8, 5, 2]⏎ |
Write the output.
L = [1, 2, 3] print(L * 2)
[1, 2, 3, 1, 2, 3]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [1, 2, 3] | L = [1, 2, 3] | |
| 2 | print(L * 2) | [1, 2, 3, 1, 2, 3]⏎ |
Write the output.
T = (4, 9, 1) print(max(T) - min(T))
8
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | T = (4, 9, 1) | T = (4, 9, 1) | |
| 2 | print(max(T) - min(T)) | 8⏎ |
Write the output.
T = (1, 2) + (3,) print(T)
(1, 2, 3)
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | T = (1, 2) + (3,) | T = (1, 2, 3) | |
| 2 | print(T) | (1, 2, 3)⏎ |
Write the output.
D = {"a": 1, "b": 2}
D["c"] = 3
print(len(D), D["b"])3 2
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {"a": 1, "b": 2} | D = {'a': 1, 'b': 2} | |
| 2 | D["c"] = 3 | D = {'a': 1, 'b': 2, 'c': 3} | |
| 3 | print(len(D), D["b"]) | 3 2⏎ |
Write the output.
D = {"x": 5}
print(D.get("y", 0))0
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {"x": 5} | D = {'x': 5} | |
| 2 | print(D.get("y", 0)) | 0⏎ |
Write the output.
D = {1: "one", 2: "two"}
print(list(D.keys()))[1, 2]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {1: "one", 2: "two"} | D = {1: 'one', 2: 'two'} | |
| 2 | print(list(D.keys())) | [1, 2]⏎ |
Write the output.
print(bool(0), bool("0"))False True
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(bool(0), bool("0")) | False True⏎ |
Write the output.
print(5 > 3 and 2 > 4 or not False)
True
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(5 > 3 and 2 > 4 or not False) | True⏎ |
Write the output.
x = 5 x += 3 * 2 print(x)
11
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | x = 5 | x = 5 | |
| 2 | x += 3 * 2 | x = 11 | |
| 3 | print(x) | 11⏎ |
Write the output.
print(type(3 / 1))
<class 'float'>
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(type(3 / 1)) | <class 'float'>⏎ |
Write the output.
print("5" + "5", 5 + 5)55 10
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("5" + "5", 5 + 5) | 55 10⏎ |
Write the output.
print(list(range(2, 11, 4)))
[2, 6, 10]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(list(range(2, 11, 4))) | [2, 6, 10]⏎ |
Write the output.
print(1 + 2 * 3 ** 2)
19
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(1 + 2 * 3 ** 2) | 19⏎ |
Write the output.
print(4 + 2 * 2 ** 2)
12
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(4 + 2 * 2 ** 2) | 12⏎ |
Write the output.
print(10 + 1 * 4 ** 2)
26
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(10 + 1 * 4 ** 2) | 26⏎ |
Write the output.
print(0 + 5 * 2 ** 2)
20
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(0 + 5 * 2 ** 2) | 20⏎ |
Write the output.
print(7 + 3 * 1 ** 2)
10
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(7 + 3 * 1 ** 2) | 10⏎ |
Write the output.
print(2 + 2 * 5 ** 2)
52
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(2 + 2 * 5 ** 2) | 52⏎ |
Write the output.
print(23 // 4, 23 % 4)
5 3
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(23 // 4, 23 % 4) | 5 3⏎ |
Write the output.
print(40 // 6, 40 % 6)
6 4
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(40 // 6, 40 % 6) | 6 4⏎ |
Write the output.
print(9 // 10, 9 % 10)
0 9
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(9 // 10, 9 % 10) | 0 9⏎ |
Write the output.
print(100 // 8, 100 % 8)
12 4
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(100 // 8, 100 % 8) | 12 4⏎ |
Write the output.
print(15 // 15, 15 % 15)
1 0
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(15 // 15, 15 % 15) | 1 0⏎ |
Write the output.
print(31 // 7, 31 % 7)
4 3
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(31 // 7, 31 % 7) | 4 3⏎ |
Write the output.
print("Computer"[2:5])mpu
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Computer"[2:5]) | mpu⏎ |
Write the output.
print("Kendriya"[0:4])Kend
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Kendriya"[0:4]) | Kend⏎ |
Write the output.
print("Database"[4:8])base
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Database"[4:8]) | base⏎ |
Write the output.
print("Network"[1:4])etw
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Network"[1:4]) | etw⏎ |
Write the output.
print("Vidyalaya"[3:7])yala
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Vidyalaya"[3:7]) | yala⏎ |
Write the output.
print("Function"[2:6])ncti
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Function"[2:6]) | ncti⏎ |
Write the output.
print("Dictionary"[4:9])ionar
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Dictionary"[4:9]) | ionar⏎ |
Write the output.
print("Sangathan"[1:5])anga
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Sangathan"[1:5]) | anga⏎ |
Write the output.
print("Computer"[::-1])retupmoC
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Computer"[::-1]) | retupmoC⏎ |
Write the output.
print("Science"[::-2])eniS
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Science"[::-2]) | eniS⏎ |
Write the output.
print("Dictionary"[::3])Dtny
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Dictionary"[::3]) | Dtny⏎ |
Write the output.
print("Examination"[::-3])ntix
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Examination"[::-3]) | ntix⏎ |
Write the output.
print("Keyboard"[::2])Kyor
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Keyboard"[::2]) | Kyor⏎ |
Write the output.
print("Monitor"[::-1])rotinoM
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("Monitor"[::-1]) | rotinoM⏎ |
Write the output.
print("new delhi".title())New Delhi
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("new delhi".title()) | New Delhi⏎ |
Write the output.
print("CLASS xii".lower())class xii
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("CLASS xii".lower()) | class xii⏎ |
Write the output.
print("sample paper".upper())SAMPLE PAPER
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("sample paper".upper()) | SAMPLE PAPER⏎ |
Write the output.
print("pYTHON".capitalize())Python
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("pYTHON".capitalize()) | Python⏎ |
Write the output.
print("data file".title())Data File
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("data file".title()) | Data File⏎ |
Write the output.
print("STACK".lower())stack
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("STACK".lower()) | stack⏎ |
Write the output.
print("my sql".upper())MY SQL
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("my sql".upper()) | MY SQL⏎ |
Write the output.
print("half yearly".capitalize())Half yearly
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("half yearly".capitalize()) | Half yearly⏎ |
Write the output.
print("programme".count("m"), "programme".find("m"))2 6
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("programme".count("m"), "programme".find("m")) | 2 6⏎ |
Write the output.
print("committee".count("t"), "committee".find("t"))2 5
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("committee".count("t"), "committee".find("t")) | 2 5⏎ |
Write the output.
print("success".count("s"), "success".find("s"))3 0
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("success".count("s"), "success".find("s")) | 3 0⏎ |
Write the output.
print("assessment".count("ss"), "assessment".find("ss"))2 1
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("assessment".count("ss"), "assessment".find("ss")) | 2 1⏎ |
Write the output.
print("referee".count("e"), "referee".find("e"))4 1
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("referee".count("e"), "referee".find("e")) | 4 1⏎ |
Write the output.
print("parallel".count("l"), "parallel".find("l"))3 4
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print("parallel".count("l"), "parallel".find("l")) | 3 4⏎ |
Write the output.
L = [5, 10, 15] L.append(20) print(L[-2:])
[15, 20]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [5, 10, 15] | L = [5, 10, 15] | |
| 2 | L.append(20) | L = [5, 10, 15, 20] | |
| 3 | print(L[-2:]) | [15, 20]⏎ |
Write the output.
L = [4, 8, 12, 16] L.pop(1) print(L)
[4, 12, 16]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [4, 8, 12, 16] | L = [4, 8, 12, 16] | |
| 2 | L.pop(1) | L = [4, 12, 16] | |
| 3 | print(L) | [4, 12, 16]⏎ |
Write the output.
L = [9, 3, 6] L.insert(0, 1) print(L[:2])
[1, 9]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [9, 3, 6] | L = [9, 3, 6] | |
| 2 | L.insert(0, 1) | L = [1, 9, 3, 6] | |
| 3 | print(L[:2]) | [1, 9]⏎ |
Write the output.
L = [2, 4] L.extend([6, 8]) print(L[1:3])
[4, 6]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [2, 4] | L = [2, 4] | |
| 2 | L.extend([6, 8]) | L = [2, 4, 6, 8] | |
| 3 | print(L[1:3]) | [4, 6]⏎ |
Write the output.
L = [7, 1, 5] L.sort() print(L[0], L[-1])
1 7
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [7, 1, 5] | L = [7, 1, 5] | |
| 2 | L.sort() | L = [1, 5, 7] | |
| 3 | print(L[0], L[-1]) | 1 7⏎ |
Write the output.
L = [1, 2, 3, 4] L.reverse() print(L[1])
3
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [1, 2, 3, 4] | L = [1, 2, 3, 4] | |
| 2 | L.reverse() | L = [4, 3, 2, 1] | |
| 3 | print(L[1]) | 3⏎ |
Write the output.
L = ["a", "b", "c"]
print(L.index("c"), len(L))2 3
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = ["a", "b", "c"] | L = ['a', 'b', 'c'] | |
| 2 | print(L.index("c"), len(L)) | 2 3⏎ |
Write the output.
L = [3, 3, 4] print(L.count(3) + sum(L))
12
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [3, 3, 4] | L = [3, 3, 4] | |
| 2 | print(L.count(3) + sum(L)) | 12⏎ |
Write the output.
print(len([14, 3, 27]), max([14, 3, 27]), min([14, 3, 27]))
3 27 3
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(len([14, 3, 27]), max([14, 3, 27]), min([14, 3, 27])) | 3 27 3⏎ |
Write the output.
print(len((8, 8, 2, 5)), max((8, 8, 2, 5)), min((8, 8, 2, 5)))
4 8 2
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(len((8, 8, 2, 5)), max((8, 8, 2, 5)), min((8, 8, 2, 5))) | 4 8 2⏎ |
Write the output.
print(len([0, -4, 9]), max([0, -4, 9]), min([0, -4, 9]))
3 9 -4
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(len([0, -4, 9]), max([0, -4, 9]), min([0, -4, 9])) | 3 9 -4⏎ |
Write the output.
print(len((100, 50)), max((100, 50)), min((100, 50)))
2 100 50
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(len((100, 50)), max((100, 50)), min((100, 50))) | 2 100 50⏎ |
Write the output.
D = {"x": 4, "y": 6}
print(D.get("y"), len(D))6 2
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {"x": 4, "y": 6} | D = {'x': 4, 'y': 6} | |
| 2 | print(D.get("y"), len(D)) | 6 2⏎ |
Write the output.
D = {"a": 1}
D["b"] = 5
print(sorted(D), sum(D.values()))['a', 'b'] 6
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {"a": 1} | D = {'a': 1} | |
| 2 | D["b"] = 5 | D = {'a': 1, 'b': 5} | |
| 3 | print(sorted(D), sum(D.values())) | ['a', 'b'] 6⏎ |
Write the output.
D = {1: 10, 2: 20}
print(D[2] - D[1], 3 in D)10 False
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {1: 10, 2: 20} | D = {1: 10, 2: 20} | |
| 2 | print(D[2] - D[1], 3 in D) | 10 False⏎ |
Write the output.
D = {"p": 9}
D.update({"q": 1})
print(list(D.values()))[9, 1]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {"p": 9} | D = {'p': 9} | |
| 2 | D.update({"q": 1}) | D = {'p': 9, 'q': 1} | |
| 3 | print(list(D.values())) | [9, 1]⏎ |
Write the output.
print(7 > 5 and 2 > 9)
False
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(7 > 5 and 2 > 9) | False⏎ |
Write the output.
print(not 4 == 4 or 3 < 8)
True
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(not 4 == 4 or 3 < 8) | True⏎ |
Write the output.
print(10 >= 10 and not 6 < 2)
True
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(10 >= 10 and not 6 < 2) | True⏎ |
Write the output.
print(5 != 5 or 1 > 0 and 2 > 3)
False
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(5 != 5 or 1 > 0 and 2 > 3) | False⏎ |
Write the output.
print(not (3 > 1 and 2 > 1))
False
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(not (3 > 1 and 2 > 1)) | False⏎ |
Write the output.
print(8 % 2 == 0 or 9 % 2 == 0)
True
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | print(8 % 2 == 0 or 9 % 2 == 0) | True⏎ |
A column in one table that matches the primary key of another table is called a ...
(c) Foreign key A foreign key links a table to the primary key of another table.
Which MySQL query shows the employees whose salary is from 90,000 to 1,00,000, both limits included?
(c) SELECT * FROM Employees WHERE salary BETWEEN 90000 AND 100000; BETWEEN includes both limits.
The set of values that an attribute is allowed to take is called its ...
(a) Domain The domain of an attribute is its set of allowed values, e.g. {'M', 'F'}.
Which property of a relation does not change when a new row is inserted?
(b) Degree Degree is the number of columns.
Which MySQL command removes the attribute Age from the table Student?
(a) ALTER TABLE Student DROP COLUMN Age; Changing the structure needs ALTER TABLE; DROP COLUMN removes a column.
A table has two candidate keys, one of which is chosen as the primary key. How many alternate keys does the table have?
(b) 1 Alternate keys = candidate keys - primary key.
Which SQL command can change the degree of an existing relation?
(b) ALTER TABLE ALTER TABLE adds or drops columns.
A relation has 2 tuples and 3 attributes. If 2 attributes are deleted and 4 tuples are added, what is the cardinality?
(c) 6 2 + 4 = 6 rows. The degree becomes 1.
Which aggregate function returns the smallest value of a column?
(a) MIN() MIN() gives the smallest value; MAX() gives the largest.
Which constraint makes sure that no two rows have the same value in a column?
(a) UNIQUE UNIQUE does not allow repeated values in the column.
Which of the following is a DML command?
(a) UPDATE DML commands change the data: INSERT, UPDATE, DELETE. CREATE, ALTER and DROP are DDL.
Which aggregate function counts the non-NULL values of a column?
(b) count() COUNT(column) counts only the values that are not NULL; COUNT(*) counts all rows.
Table A has 6 rows and 3 columns; table B has 5 rows and 2 columns. Their Cartesian product has ...
(a) 30 rows and 5 columns Rows multiply, columns add.
Values of which MySQL data type are written without quotes?
(c) FLOAT Numbers (INT, FLOAT, DECIMAL) are written without quotes; text and dates need quotes.
A row of a relation is called a ...
(b) tuple Each row holds one record and is called a tuple.
A column of a relation is called a/an ...
(b) attribute A column is an attribute; a row is a tuple.
The number of rows in a relation is called its ...
(b) cardinality Cardinality = number of rows; degree = number of columns.
How many primary keys can a table have?
(a) Only one A table can have many candidate keys but one primary key.
Candidate keys that are not chosen as the primary key are called ...
(b) alternate keys The remaining candidate keys are called alternate keys.
Which of the following is a DDL command?
(c) CREATE DDL commands define the structure: CREATE, ALTER, DROP.
Which command removes all the rows of a table but keeps the table?
(b) DELETE FROM DELETE FROM table; without WHERE removes all the rows but the empty table remains.
Which command removes a table together with its structure?
(b) DROP TABLE DROP TABLE removes the table itself, with its structure and data.
Which clause arranges the output in sorted order?
(b) ORDER BY ORDER BY column sorts the result (ASC by default, DESC for descending).
The default order of the ORDER BY clause is ...
(a) ascending Write DESC for descending order.
Which keyword removes duplicate values from the output of SELECT?
(b) DISTINCT SELECT DISTINCT city shows each city only once.
In a LIKE pattern, which symbol stands for exactly one character?
(b) _ _ stands for exactly one character; % stands for any number of characters.
In a LIKE pattern, which symbol stands for zero or more characters?
(a) % % stands for zero or more characters; _ stands for exactly one.
Which is the correct way to find rows where Phone has no value?
(b) WHERE Phone IS NULL NULL means unknown, so = NULL never matches; IS NULL is used.
Which clause puts a condition on groups made by GROUP BY?
(b) HAVING HAVING filters the groups; WHERE filters the rows before grouping.
COUNT(*) counts ...
(b) all the rows COUNT(*) counts every row, including rows that have NULL values.
Which data type is best for a date of birth?
(b) DATE DATE stores dates in the form 'YYYY-MM-DD' and allows date functions.
A CHAR(10) column that stores 'Ram' uses space for ...
(b) 10 characters CHAR has a fixed length.
A VARCHAR(10) column that stores 'Ram' uses space for ...
(a) 3 characters VARCHAR has a variable length.
Which command shows the structure of a table?
(b) DESC DESC or DESCRIBE.
Which command opens a database for use?
(b) USE USE school; makes school the current database.
Which command lists all the tables of the current database?
(a) SHOW TABLES; SHOW TABLES; lists the tables of the database in use.
Which command changes the data stored in existing rows?
(b) UPDATE UPDATE ... SET ... WHERE changes values in existing rows.
Which command adds a new column to an existing table?
(b) ALTER TABLE ... ADD ALTER TABLE STUDENT ADD Phone VARCHAR(10); adds a column.
In which join does the common column appear only once in the output?
(c) Natural join NATURAL JOIN joins on the common column and shows it only once; an equi-join shows it twice.
The Cartesian product of a table with 4 rows and a table with 3 rows has ______ rows.
(b) 12 4 x 3 = 12.
A PRIMARY KEY constraint is the same as ...
(a) UNIQUE + NOT NULL A primary key value must be unique and cannot be NULL.
Which method runs an SQL query from a Python program?
(b) execute() It is a method of the cursor object.
Which method saves the changes made by INSERT, UPDATE or DELETE permanently?
(b) commit() It is a method of the connection object.
fetchall() returns ...
(b) a list of tuples Each tuple is one row.
A relation has 4 tuples and 5 attributes. 3 more tuples are added and 1 attribute is removed. What is its degree now?
(c) 4 Degree = 5 - 1 = 4 columns; cardinality = 4 + 3 = 7 rows.
A relation has 4 tuples and 5 attributes. 3 more tuples are added and 1 attribute is removed. What is its cardinality now?
(d) 7 Degree = 5 - 1 = 4 columns; cardinality = 4 + 3 = 7 rows.
A relation has 10 tuples and 3 attributes. 5 more tuples are added and 0 attributes are removed. What is its cardinality now?
(b) 15 Degree = 3 - 0 = 3 columns; cardinality = 10 + 5 = 15 rows.
A relation has 10 tuples and 3 attributes. 0 more tuples are added and 1 attribute is removed. What is its degree now?
(a) 2 Degree = 3 - 1 = 2 columns; cardinality = 10 + 0 = 10 rows.
A relation has 6 tuples and 6 attributes. 2 more tuples are added and 2 attributes are removed. What is its degree now?
(a) 4 Degree = 6 - 2 = 4 columns; cardinality = 6 + 2 = 8 rows.
A relation has 6 tuples and 6 attributes. 2 more tuples are added and 2 attributes are removed. What is its cardinality now?
(d) 8 Degree = 6 - 2 = 4 columns; cardinality = 6 + 2 = 8 rows.
A relation has 8 tuples and 4 attributes. 4 more tuples are added and 1 attribute is removed. What is its cardinality now?
(c) 12 Degree = 4 - 1 = 3 columns; cardinality = 8 + 4 = 12 rows.
A relation has 8 tuples and 4 attributes. 4 more tuples are added and 1 attribute is removed. What is its degree now?
(d) 3 Degree = 4 - 1 = 3 columns; cardinality = 8 + 4 = 12 rows.
A relation has 3 tuples and 7 attributes. 9 more tuples are added and 3 attributes are removed. What is its degree now?
(d) 4 Degree = 7 - 3 = 4 columns; cardinality = 3 + 9 = 12 rows.
A relation has 3 tuples and 7 attributes. 9 more tuples are added and 3 attributes are removed. What is its cardinality now?
(a) 12 Degree = 7 - 3 = 4 columns; cardinality = 3 + 9 = 12 rows.
A relation has 12 tuples and 5 attributes. 1 more tuples are added and 2 attributes are removed. What is its degree now?
(a) 3 Degree = 5 - 2 = 3 columns; cardinality = 12 + 1 = 13 rows.
A relation has 12 tuples and 5 attributes. 1 more tuples are added and 2 attributes are removed. What is its cardinality now?
(b) 13 Degree = 5 - 2 = 3 columns; cardinality = 12 + 1 = 13 rows.
A relation has 5 tuples and 2 attributes. 5 more tuples are added and 0 attributes are removed. What is its cardinality now?
(d) 10 Degree = 2 - 0 = 2 columns; cardinality = 5 + 5 = 10 rows.
A relation has 7 tuples and 8 attributes. 0 more tuples are added and 4 attributes are removed. What is its degree now?
(b) 4 Degree = 8 - 4 = 4 columns; cardinality = 7 + 0 = 7 rows.
A relation has 9 tuples and 6 attributes. 6 more tuples are added and 3 attributes are removed. What is its cardinality now?
(b) 15 Degree = 6 - 3 = 3 columns; cardinality = 9 + 6 = 15 rows.
A relation has 2 tuples and 9 attributes. 8 more tuples are added and 5 attributes are removed. What is its degree now?
(b) 4 Degree = 9 - 5 = 4 columns; cardinality = 2 + 8 = 10 rows.
Table P has 3 rows and 2 columns. Table Q has 4 rows and 3 columns. How many rows does their Cartesian product have?
(c) 12 Rows multiply (3 x 4); columns add (2 + 3).
Table P has 3 rows and 2 columns. Table Q has 4 rows and 3 columns. How many columns does their Cartesian product have?
(b) 5 Rows multiply (3 x 4); columns add (2 + 3).
Table P has 5 rows and 4 columns. Table Q has 2 rows and 2 columns. How many rows does their Cartesian product have?
(c) 10 Rows multiply (5 x 2); columns add (4 + 2).
Table P has 5 rows and 4 columns. Table Q has 2 rows and 2 columns. How many columns does their Cartesian product have?
(a) 6 Rows multiply (5 x 2); columns add (4 + 2).
Table P has 6 rows and 3 columns. Table Q has 3 rows and 5 columns. How many rows does their Cartesian product have?
(d) 18 Rows multiply (6 x 3); columns add (3 + 5).
Table P has 7 rows and 2 columns. Table Q has 2 rows and 6 columns. How many columns does their Cartesian product have?
(a) 8 Rows multiply (7 x 2); columns add (2 + 6).
Table P has 10 rows and 3 columns. Table Q has 3 rows and 2 columns. How many rows does their Cartesian product have?
(a) 30 Rows multiply (10 x 3); columns add (3 + 2).
Table P has 4 rows and 4 columns. Table Q has 4 rows and 4 columns. How many columns does their Cartesian product have?
(a) 8 Rows multiply (4 x 4); columns add (4 + 4).
Table P has 8 rows and 5 columns. Table Q has 5 rows and 1 columns. How many rows does their Cartesian product have?
(c) 40 Rows multiply (8 x 5); columns add (5 + 1).
Table P has 9 rows and 2 columns. Table Q has 2 rows and 3 columns. How many columns does their Cartesian product have?
(a) 5 Rows multiply (9 x 2); columns add (2 + 3).
The column marks of a table has the values 40, NULL, 60, 80. What does SELECT COUNT(marks) FROM t; return?
(d) 3 COUNT(*) counts every row. The other aggregate functions skip NULL.
The column marks of a table has the values 40, NULL, 60, 80. What does SELECT COUNT(*) FROM t; return?
(b) 4 COUNT(*) counts every row. The other aggregate functions skip NULL.
The column marks of a table has the values 10, 20, NULL, 30. What does SELECT SUM(marks) FROM t; return?
(c) 60 COUNT(*) counts every row. The other aggregate functions skip NULL.
The column marks of a table has the values 10, 20, NULL, 30. What does SELECT AVG(marks) FROM t; return?
(b) 20 COUNT(*) counts every row. The other aggregate functions skip NULL.
The column marks of a table has the values 55, 90, NULL, 70. What does SELECT MAX(marks) FROM t; return?
(a) 90 COUNT(*) counts every row. The other aggregate functions skip NULL.
The column marks of a table has the values 55, 90, NULL, 70. What does SELECT MIN(marks) FROM t; return?
(a) 55 COUNT(*) counts every row. The other aggregate functions skip NULL.
The column marks of a table has the values NULL, NULL, 50. What does SELECT COUNT(marks) FROM t; return?
(d) 1 COUNT(*) counts every row. The other aggregate functions skip NULL.
The column marks of a table has the values 25, 75, NULL. What does SELECT AVG(marks) FROM t; return?
(c) 50 COUNT(*) counts every row. The other aggregate functions skip NULL.
The column marks of a table has the values 5, 5, NULL, 5, 5. What does SELECT SUM(marks) FROM t; return?
(d) 20 COUNT(*) counts every row. The other aggregate functions skip NULL.
The column marks of a table has the values NULL, 12, 12, NULL. What does SELECT COUNT(*) FROM t; return?
(c) 4 COUNT(*) counts every row. The other aggregate functions skip NULL.
Which of these names is selected by the condition name LIKE 'S_m%'?
(a) Suman % stands for any number of characters and _ for exactly one character.
Which of these names is selected by the condition name LIKE '%an'?
(b) Aman % stands for any number of characters and _ for exactly one character.
Which of these names is selected by the condition name LIKE '_a%'?
(d) Ravi % stands for any number of characters and _ for exactly one character.
Which of these names is selected by the condition name LIKE 'A%a'?
(a) Anita % stands for any number of characters and _ for exactly one character.
Which of these names is selected by the condition name LIKE '%e%'?
(a) Neha % stands for any number of characters and _ for exactly one character.
Which of these names is selected by the condition name LIKE '____'?
(d) Asha % stands for any number of characters and _ for exactly one character.
Which of these names is selected by the condition name LIKE 'R%'?
(b) Ritu % stands for any number of characters and _ for exactly one character.
Which of these names is selected by the condition name LIKE '%i'?
(b) Ravi % stands for any number of characters and _ for exactly one character.
Which of these names is selected by the condition name LIKE '_i%a'?
(d) Tina % stands for any number of characters and _ for exactly one character.
Which of these names is selected by the condition name LIKE '%sh%'?
(d) Asha % stands for any number of characters and _ for exactly one character.
A column x has the values 10, 20, 30, 40, 50. How many rows satisfy WHERE x BETWEEN 20 AND 40?
(c) 3 BETWEEN includes both of its limits.
A column x has the values 5, 15, 25, 35. How many rows satisfy WHERE x IN (5, 25, 45)?
(b) 2 BETWEEN includes both of its limits.
A column x has the values 33, 60, 75, 90, 100. How many rows satisfy WHERE x BETWEEN 60 AND 90?
(d) 3 BETWEEN includes both of its limits.
A column x has the values 1, 2, 3, 4, 5, 6. How many rows satisfy WHERE x NOT IN (2, 4)?
(b) 4 BETWEEN includes both of its limits.
A column x has the values 12, 18, 24, 30. How many rows satisfy WHERE x NOT BETWEEN 18 AND 24?
(b) 2 BETWEEN includes both of its limits.
A column x has the values 7, 14, 21, 28, 35. How many rows satisfy WHERE x > 14 AND x <= 28?
(a) 2 BETWEEN includes both of its limits.
Which clause is used with aggregate functions to make one group for every city?
(b) GROUP BY city GROUP BY city makes one group per city; the aggregate is worked out for each group.
Which command makes RNo the primary key of an existing table STUDENT?
(a) ALTER TABLE STUDENT ADD PRIMARY KEY (RNo); ALTER TABLE ... ADD PRIMARY KEY (column) adds a primary key to an existing table.
Which of the following is not a constraint?
(d) ORDER BY ORDER BY is a clause of SELECT.
Which command lists all the databases on the server?
(a) SHOW DATABASES; SHOW DATABASES; lists the databases; SHOW TABLES; lists the tables of the current database.
In SELECT name AS Student FROM s; the word Student is ...
(b) an alias (temporary heading) for the column AS gives a temporary heading (alias) to the column in the output.
Which operator is used in the join condition of an equi join?
(b) = An equi-join matches rows with =, e.g. A.ID = B.ID.
Which command removes the database school completely?
(b) DROP DATABASE school; DROP DATABASE removes the database with all its tables.
In ORDER BY marks DESC, the word DESC means ...
(b) descending order DESC sorts from the largest to the smallest; ASC (default) sorts from the smallest.
Which medium is used for long-distance communication where line of sight is not possible?
(c) Radio waves Radio waves spread in all directions and pass through walls, so no line of sight is needed.
Every network interface card (NIC) comes with its own ______ address.
(c) Physical (MAC) Each NIC has a unique 48-bit physical (MAC) address burnt in by the maker.
In ______ switching, a dedicated path is set up between sender and receiver before the data transfer starts.
(c) Circuit In circuit switching (as in old telephone calls) a fixed path is reserved before talking starts.
With respect to computer networks, which is the correct expanded form of RJ45?
(d) Registered Jack 45 RJ45 = Registered Jack 45, the connector used on Ethernet cables.
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?
(b) Gateway A gateway is the entry and exit point of a network and connects it to other networks.
Expand XML.
(a) eXtensible Markup Language XML = eXtensible Markup Language, used to store and carry data with user-defined tags.
Which networking device is used to regenerate and transmit a weakened signal ahead?
(c) Repeater A repeater boosts (regenerates) a weak signal so it can travel further.
Which protocol is used to make phone calls over the Internet?
(d) VoIP Voice over Internet Protocol.
Expand ARPANET.
(a) Advanced Research Projects Agency Network ARPANET = Advanced Research Projects Agency Network, the first network that grew into the Internet.
Which device connects computers in a LAN and sends data only to the intended computer?
(b) Switch A switch learns the MAC addresses and sends data only to the destination computer.
Which protocol is used for sending e-mail?
(b) SMTP Simple Mail Transfer Protocol.
A network that covers one city is called a ...
(b) MAN Metropolitan Area Network.
In which topology does the failure of the central device stop the whole network?
(b) Star In a star, all computers depend on the central hub or switch.
Which wired medium gives the highest speed and is not affected by electrical interference?
(c) Optical fibre Optical fibre carries light, so it is very fast and free from electrical interference.
A network of computers inside one school building is a ...
(a) LAN Local Area Network.
A phone connected to a Bluetooth headset forms a ...
(d) PAN Personal Area Network.
The Internet is the largest example of a ...
(c) WAN The Internet connects networks all over the world, so it is a WAN.
Which device changes digital signals to analog signals and back?
(a) Modem MOdulator-DEModulator.
Which device connects different networks and chooses the best path for data?
(b) Router A router connects networks and picks the best route for each packet.
Which device sends the data it receives to all the connected computers?
(a) Hub A hub broadcasts data to every port, unlike a switch.
Which protocol is used to transfer files between computers?
(a) FTP File Transfer Protocol.
Which protocol is used to receive e-mail from the mail server?
(b) POP3 Post Office Protocol version 3.
Which protocol is used for secure web pages, such as online payment?
(b) HTTPS The S stands for Secure.
Which protocol is used to log in to a remote computer?
(a) TELNET TELNET lets a user log in to and work on a remote computer.
Expand TCP.
(b) Transmission Control Protocol TCP = Transmission Control Protocol; it breaks data into packets and makes sure they arrive correctly.
Expand HTTP.
(a) HyperText Transfer Protocol HTTP = HyperText Transfer Protocol, used to transfer web pages.
Expand URL.
(b) Uniform Resource Locator URL = Uniform Resource Locator, the address of a web page.
Expand WWW.
(a) World Wide Web WWW = World Wide Web, the system of linked web pages on the Internet.
Expand NIC.
(b) Network Interface Card NIC = Network Interface Card, which connects a computer to a network.
Expand MAC in MAC address.
(a) Media Access Control MAC = Media Access Control.
An IPv4 address has ______ bits.
(b) 32 IPv6 has 128 bits.
A MAC address has ______ bits.
(b) 48 It is written as 6 pairs of hexadecimal digits.
Bandwidth is measured in ...
(a) Hertz Bandwidth (range of frequencies) is measured in Hertz; data rate is measured in bps.
Data transfer rate is measured in ...
(b) bps bits per second: Kbps, Mbps, Gbps.
Which medium carries data in the form of light?
(c) Optical fibre Optical fibre sends data as pulses of light.
A TV remote control uses ...
(c) infrared waves A TV remote uses infrared waves, which need line of sight and work over short distances.
Which wireless medium needs the sending and receiving towers to be in line of sight?
(b) Microwaves Microwaves travel in straight lines, so the towers must face each other.
Which cable is commonly used for cable TV connections?
(b) Coaxial cable Coaxial cable is used for cable TV.
In which topology are all the computers connected to one backbone cable?
(a) Bus In a bus topology every computer is joined to a single backbone cable.
Which topology is a combination of bus and star topologies?
(c) Tree Tree topology joins several star networks to a bus backbone.
In XML, the tags are ...
(b) created by the user HTML tags are predefined.
Which of the following is a web browser?
(b) Mozilla Firefox A browser such as Firefox, Chrome or Edge opens web pages.
The service of storing a website on a web server so that it can be opened on the Internet is called ...
(b) web hosting Web hosting keeps the website's files on a server connected to the Internet.
In packet switching, the message is ...
(b) divided into small packets The packets may take different routes.
Which topology has a hierarchical structure, with branches joined to a backbone?
(c) Tree Tree topology looks like a tree: branches (stars) joined to a backbone.
Which device is needed to connect a computer to the Internet through a telephone line?
(a) Modem A modem converts digital signals to analog (modulation) and back (demodulation).
Which card lets a computer join a wireless network?
(b) Wi-Fi card A Wi-Fi card (wireless NIC) connects a computer to a wireless network.
Which of the following is not a wired medium?
(d) Microwave Microwave is wireless; twisted pair, coaxial cable and optical fibre are wired.
Which of the following is not a protocol?
(c) Router A router is a device.
Which protocol is used for a direct connection between two nodes?
(a) PPP Point-to-Point Protocol.
Which type of network covers the largest area?
(d) WAN PAN < LAN < MAN < WAN: a WAN covers countries and continents.
The complete address of a web page typed in the browser is called its ...
(a) URL The URL is the full web address, e.g. https://www.cbse.gov.in/index.html.
Which of the following is a valid IPv4 address?
(a) 192.168.1.10 Four numbers from 0 to 255, separated by dots.
Which device connects two networks that use different protocols?
(c) Gateway A gateway translates between networks that use different protocols.
Expand HTML.
(a) HyperText Markup Language HTML = HyperText Markup Language, used to make web pages.
Expand SMTP.
(a) Simple Mail Transfer Protocol SMTP = Simple Mail Transfer Protocol, used to send e-mail.
Expand POP3.
(a) Post Office Protocol version 3 POP3 = Post Office Protocol version 3, used to download e-mail from the server.
Expand VoIP.
(b) Voice over Internet Protocol VoIP = Voice over Internet Protocol: voice calls over the Internet.
Expand NSFNET.
(a) National Science Foundation Network NSFNET = National Science Foundation Network, which later became a part of the Internet backbone.
Which of the following is a domain name?
(a) cbse.gov.in cbse.gov.in is a domain name; .in is the country domain and .gov shows a government site.
Which of the following is a web server?
(a) Apache The other three are web browsers.
Kbps stands for ...
(b) kilobits per second Kbps = kilobits per second, a unit of data rate.
Six computers are connected to one switch in star topology. How many cables go to the switch?
(c) 6 Every computer has its own cable.
Which switching technique is used on the Internet?
(b) Packet switching In packet switching, data is broken into packets that travel separately and are joined at the destination.
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.
(c) A is true but R is false. Read modes give an error when the file is missing.
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.
(c) A is true but R is false. NULL is tested only with IS NULL / IS NOT NULL.
Assertion (A): The expression [1, 2, 3] + '123' is invalid.
Reason (R): A list cannot be concatenated with a string.
(a) Both A and R are true and R is the correct explanation of A. The + operator needs both operands to be lists.
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.
(c) A is true but R is false. The primary key is chosen from the candidate keys.
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.
(c) A is true but R is false. dump() writes; load() reads. Writing is not allowed in rb mode.
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.
(a) Both A and R are true and R is the correct explanation of A. The join condition uses the common (foreign key) column.
Assertion (A): A Python function can return more than one value.
Reason (R): Multiple values are returned in the form of a tuple.
(a) Both A and R are true and R is the correct explanation of A. return a, b sends back the tuple (a, b).
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.
(c) A is true but R is false. That is a (append) mode. w starts with an empty file.
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.
(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).
Assertion (A): DELETE FROM student; removes the table structure from the database.
Reason (R): DELETE is a DML command.
(d) A is false but R is true. DELETE removes rows only. DROP TABLE removes the structure.
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.
(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).
Assertion (A): COUNT(*) and COUNT(Phone) can give different answers for the same table.
Reason (R): COUNT(column) ignores NULL values.
(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).
Assertion (A): A tuple can be used as a key of a dictionary.
Reason (R): A tuple is immutable.
(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).
Assertion (A): L = [1, 2, 3] followed by L[0] = 9 is valid.
Reason (R): Lists are mutable.
(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).
Assertion (A): s = "abc" followed by s[0] = "x" gives an error.
Reason (R): Strings are immutable.
(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).
Assertion (A): A default parameter must be written after the non-default parameters.
Reason (R): Python matches positional arguments from left to right.
(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).
Assertion (A): A local variable can be used outside its function.
Reason (R): A local variable is created when the function is called.
(d) A is false but R is true. A local variable exists only inside its function.
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.
(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).
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.
(d) A is false but R is true. finally runs in every case.
Assertion (A): 10 / 0 raises ZeroDivisionError.
Reason (R): Division by zero is not defined.
(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).
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.
(c) A is true but R is false. else comes after all the except blocks.
Assertion (A): A file opened in r mode must already exist.
Reason (R): r mode creates a new file when the file is missing.
(c) A is true but R is false. It raises FileNotFoundError.
Assertion (A): readlines() returns a list.
Reason (R): read() returns the whole file as one string.
(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.
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.
(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).
Assertion (A): pickle.load() is written inside try-except while reading all the records.
Reason (R): load() raises EOFError when no record is left.
(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).
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.
(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.
Assertion (A): f.tell() changes the position of the file pointer.
Reason (R): f.seek() moves the file pointer.
(d) A is false but R is true. tell() only reports the position.
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.
(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).
Assertion (A): Popping from an empty stack is called overflow.
Reason (R): A stack follows LIFO.
(d) A is false but R is true. It is called underflow.
Assertion (A): A table can have many candidate keys.
Reason (R): A table can have only one primary key.
(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.
Assertion (A): A foreign key column can have repeated values.
Reason (R): A foreign key refers to the primary key of another table.
(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).
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.
(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).
Assertion (A): DROP TABLE is a DML command.
Reason (R): DROP TABLE removes the table with its structure.
(d) A is false but R is true. DROP is a DDL command.
Assertion (A): SELECT DISTINCT city FROM student; shows every city only once.
Reason (R): DISTINCT removes duplicate values from the output.
(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).
Assertion (A): ORDER BY marks shows the highest marks first.
Reason (R): The default order of ORDER BY is ascending.
(d) A is false but R is true. A is false: ascending is the default (R is true), so the lowest marks come first.
Assertion (A): LIKE 'A%' matches both "Aman" and "A".
Reason (R): % stands for zero or more characters.
(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).
Assertion (A): commit() is needed after an INSERT query run from Python.
Reason (R): Changes are not saved permanently until commit() is called.
(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).
Assertion (A): commit() is needed after a SELECT query run from Python.
Reason (R): A SELECT query does not change the data.
(d) A is false but R is true. A is false: SELECT only reads data (R is true), so nothing needs to be saved.
Assertion (A): Optical fibre is not affected by electrical interference.
Reason (R): Optical fibre carries data in the form of light.
(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).
Assertion (A): A hub is called an intelligent device.
Reason (R): A hub sends the data to all the connected devices.
(d) A is false but R is true. A switch is the intelligent device.
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.
(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).
Assertion (A): HTTPS is safer than HTTP.
Reason (R): HTTPS encrypts the data sent between the browser and the server.
(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).
Assertion (A): SELECT * FROM A, B; gives the Cartesian product of the two tables.
Reason (R): No join condition is given in the query.
(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).
Assertion (A): COUNT(*) also counts the rows that have NULL values.
Reason (R): COUNT(*) counts all the rows of the table.
(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).
Assertion (A): UPDATE student SET marks = 0; changes every row of the table.
Reason (R): The query has no WHERE clause.
(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).
Assertion (A): A primary key column can hold NULL.
Reason (R): A primary key identifies every row uniquely.
(d) A is false but R is true. A primary key is never NULL.
Assertion (A): WHERE name LIKE '_a%' selects the name "Ravi".
Reason (R): In a LIKE pattern, _ stands for exactly one character.
(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).
Assertion (A): ALTER TABLE is a DDL command.
Reason (R): ALTER TABLE changes the structure of a table.
(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).
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.
(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).
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.
(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).
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.
(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).
Explain global and local variables with an example.
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()Differentiate between seek() and tell().
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()) # 5Differentiate between ALTER and UPDATE with an example of each.
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;
Differentiate between default and positional parameters. Write a function header that uses both.
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 * bWhat is the role of the return statement in a function? Give an example.
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 10Give one example each of:
(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
Differentiate between a text file and a binary file.
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.
Differentiate between read() and readlines().
read() returns the whole file as one string. readlines() returns a list of strings, one for each line.
Differentiate between the file modes w and a.
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.
Differentiate between an argument and a parameter.
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 argumentDifferentiate between DELETE and DROP.
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;
Differentiate between the WHERE and HAVING clauses.
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;
Differentiate between mutable and immutable data types with one example of each.
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.
Differentiate between a list and a tuple.
A list is written in [ ] and is mutable. A tuple is written in ( ) and is immutable, so it has no append() or remove().
Differentiate between == and is.
== checks whether two objects have the same value. is checks whether two names refer to the same object in memory.
Differentiate between break and continue.
break ends the loop at once. continue skips the remaining statements of the current round and goes to the next round of the loop.
Differentiate between / and //.
/ 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.
Differentiate between append() and extend().
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].
Differentiate between pop() and remove() of a list.
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.
Differentiate between sort() and sorted().
L.sort() arranges the list L itself and returns None. sorted(L) returns a new sorted list and leaves L unchanged.
Differentiate between find() and index() of a string.
Both return the position of a substring. When the substring is not found, find() returns -1 but index() raises ValueError.
Differentiate between a syntax error and a run-time error.
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.
Differentiate between a built-in function and a user-defined function.
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.
Differentiate between a keyword and an identifier.
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.
Differentiate between positional and keyword arguments.
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).
What is the scope of a variable? Name the two types of scope.
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.
What is the use of the try and except blocks?
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.
What is the use of the finally block?
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.
Differentiate between the file modes r+ and w+.
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.
Differentiate between readline() and readlines().
readline() reads one line and returns it as a string. readlines() reads all the lines and returns them as a list of strings.
Differentiate between write() and writelines().
write(s) writes one string. writelines(L) writes all the strings of a list. Neither adds a newline by itself.
Differentiate between dump() and load() of the pickle module.
pickle.dump(obj, f) writes a Python object to a binary file. pickle.load(f) reads one object back from the binary file.
Why should a file be closed? What is the advantage of the with statement?
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.
Differentiate between a relative path and an absolute path.
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.
What is a CSV file? Write two advantages.
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.
Differentiate between writerow() and writerows().
writerow(L) writes one record (one list). writerows(LL) writes many records at once (a list of lists).
What is a stack? Write two uses of a stack.
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.
Differentiate between overflow and underflow in a stack.
Overflow: trying to push an item into a stack that is full. Underflow: trying to pop an item from a stack that is empty.
Differentiate between a primary key and a foreign key.
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.
Differentiate between degree and cardinality with an example.
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.
Differentiate between CHAR and VARCHAR.
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.
Differentiate between fetchone() and fetchall().
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.
What is a default parameter? Give an example.
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.
Differentiate between a function definition and a function call.
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.
Differentiate between the file modes r and rb.
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().
Differentiate between the file modes a and a+.
Both add new data at the end and keep the old data. a allows only writing. a+ allows writing and reading.
Differentiate between print() and return inside a function.
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.
Differentiate between a list and a dictionary.
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.
What is EOFError? When does it occur while reading a binary file?
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.
Differentiate between the operators in and not in with an example.
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.
Differentiate between isalpha() and isalnum().
isalpha() is True when the string has only letters: "abc".isalpha(). isalnum() is True when it has only letters and digits: "abc12".isalnum().
Differentiate between strip() and split().
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.
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])
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
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)
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
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)
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
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))
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
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")
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
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])
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
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]))
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
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)
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)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"))
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
The program should display the contents of notes.txt.
Given code:
f = open("notes.txt", r)
data = f.read
print(Data)
f.close
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()The program should handle the error raised by a wrong number.
Given code:
try
x = int("12a")
except valueError:
print("Invalid")
finaly:
print("Done")
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
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])
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
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"))
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
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")
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
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])
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]
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)
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
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))
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
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)
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
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")
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
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"))
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
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])
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
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])
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]
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)
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
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)
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
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)
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
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})
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'}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"))
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
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))
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
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))
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
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)
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]
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)
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
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'))
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)
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})
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']
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
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]
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])
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}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))
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
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])
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)
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)
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
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)
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}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)
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
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)
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
Write a statement to:
username starts with "admin"data.username.startswith("admin")
data.count(max(data))Write a statement to:
L1 of list L without changing Lch is a letter or a digit.L1 = sorted(L) ch.isalnum()
D1 is a dictionary. Write an expression to:
'RNo' in D1 12 in D1.values()
D1 is a dictionary. Write a statement to:
D1.setdefault('RNo', 12)
D1.clear()Write a statement to:
DD1.D.get("Raj")
len(D1)Write a statement to:
D to D1D1.D1.update(D)
D1.pop("Amit")Write a statement to:
L and store it in xL2 at the end of L.x = L.pop() L.extend(L2)
Write a statement to:
s into a list of wordsW with a hyphen.W = s.split() "-".join(W)
Write a statement to:
ss.s.find('a')
s.count('a')Write a statement to:
s contains only digitss.s.isdigit() s.strip()
Write a statement to:
LL.L.insert(2, 50) L.remove(30)
Write a statement to:
TD in sorted order.print(max(T)) print(sorted(D.keys()))
Write a Python statement to:
s to capital letterss ends with ".py".s.upper()
s.endswith(".py")Write a Python statement to:
s with "@"s.s.replace("a", "@")
len(s)Write a Python statement to:
L in placeL in descending order.L.reverse() L.sort(reverse=True)
Write a Python statement to:
LL.L.index(25) L.count(25)
Write a Python statement to:
LL.L.pop(2) L.clear()
Write a Python statement to:
LL.L[-3:] L[::2]
Write a Python statement to:
LL.min(L) sum(L)
Write a Python statement to:
T into a listT.list(T) len(T)
Write a Python statement to:
TT.5 in T T.index(5)
Write a Python statement to:
DD.print(D.keys()) print(D.values())
Write a Python statement to:
DD["City"] = "Delhi" D.popitem()
Write a Python statement to:
DD named D2.D.items() D2 = D.copy()
Write a Python statement to:
s are smalls capital.s.islower() s.title()
Write a Python statement to:
ss has only letters.s.lstrip() s.isalpha()
Write a Python statement to:
s at every commas.s.split(",")
len(s.split())Write a Python statement to:
random is already imported.)random.randint(1, 6) random.random()
Write a Python statement to:
math is already imported.)math.sqrt(49) math.pow(2, 5)
Write a Python statement to:
ff = open("data.txt", "r")
f.read(10)Write a Python statement to:
f to the beginningf.seek(0) print(f.tell())
Write a Python statement to:
rec into the binary file ff.pickle.dump(rec, f) rec = pickle.load(f)
Write a Python statement to:
w for the file fw = csv.writer(f) w.writerow([1, "Asha"])
Write a Python statement to:
stst.append(25) st[-1]
Write a Python statement to:
st into xst is empty.x = st.pop() len(st) == 0
Write a Python statement to:
cur from the connection concur = con.cursor()
cur.execute("SELECT * FROM student")Write a Python statement to:
datadata = cur.fetchall() cur.rowcount
Write a Python statement to:
con.con.commit() con.close()
Write a Python statement to:
int("45")
float(7)Write a Python statement to:
ss.s[:3] s[-1]
Write a Python statement to:
L with a space between thems three times." ".join(L) s * 3
Write a Python statement to:
a, b, cx.max(a, b, c) abs(x)
Write a Python statement to:
ss are capital."KV" in s s.isupper()
Write a Python statement to:
ss.s.count(" ")
s.find(" ")Write a Python statement to:
ss starts with "The".s.rstrip()
s.startswith("The")Write a Python statement to:
ss in reverse order.s[-3:] s[::-1]
Write a Python statement to:
s capitals.s.capitalize() len(s.split())
Write a Python statement to:
s into three parts at the first "="s has only letters and digits.s.partition("=")
s.isalnum()Write a Python statement to:
LL and store it in x.L.insert(0, 99) x = L.pop(0)
Write a Python statement to:
Lmax(L) L.index(max(L))
Write a Python statement to:
M with the elements of L in descending orderL.M = sorted(L, reverse=True) len(L)
Write a Python statement to:
T at the end of list LL.L.extend(T) 10 in L
Write a Python statement to:
LL from index 1 to index 3.(L[0], L[-1]) L[1:4]
Write a Python statement to:
L into a tupleT.tuple(L) T.count(0)
Write a Python statement to:
TT.sum(T) min(T)
Write a Python statement to:
DD = {}
D[1] = "one"Write a Python statement to:
D, or 0 if the key is missingx.D.get("Age", 0)
x = D.pop("Age")Write a Python statement to:
D in sorted orderD.sorted(D) max(D.values())
Write a Python statement to:
D with the keys of list K, every value being 0D.D = dict.fromkeys(K, 0) len(D)
Write a Python statement to:
D"RNo" not in D D["RNo"] = 15
Write a Python statement to:
f for adding data at the endf = open("notes.txt", "a")
f.write("Bye\n")Write a Python statement to:
ff into a list L.f.readline() L = f.readlines()
Write a Python statement to:
f for readingf.f = open("data.dat", "rb")
f.close()Write a Python statement to:
r for the file fr = csv.reader(f) next(r)
Write a Python statement to:
f for writing so that no blank lines come between rowsLL in one call with the writer w.f = open("m.csv", "w", newline="")
w.writerows(LL)Write a Python statement to:
stx only when the stack is not empty.len(st) if len(st) > 0: x = st.pop()
Write a Python statement to:
math is already imported.)math.ceil(4.3) math.floor(4.3)
Write a Python statement to:
LL. (statistics is already imported.)statistics.mean(L) statistics.median(L)
Write a Python statement to:
randrange(). (random is already imported.)random.randint(10, 20) random.randrange(10)
Write a Python statement to:
float("3.5")
str(25)Write a Python statement to:
n is evenn is divided by 7.n % 2 == 0 n % 7
Write a Python statement to:
s to small letterss with an underscore.s.lower()
s.replace(" ", "_")Write the output of the code.
text = "Python Programming"
print(text.replace("o", "0"))
print(text.find("z"))
Output:
Pyth0n Pr0gramming -1
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | text = "Python Programming" | text = 'Python Programming' | |
| 2 | print(text.replace("o", "0")) | Pyth0n Pr0gramming⏎ | |
| 3 | print(text.find("z")) | -1⏎ |
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)
Output:
['#', 'l', '#', 'd', 10]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | s = "gLaD5" | s = 'gLaD5' | |
| 2 | L = [] | L = [] | |
| 3 | i = 0 | i = 0 | |
| 4 | while i < len(s): | condition is True | |
| 5 | if s[i].isupper(): | condition is False | |
| 7 | elif s[i].isdigit(): | condition is False | |
| 10 | L.append("#") | L = ['#'] | |
| 11 | i += 1 | i = 1 | |
| 4 | while i < len(s): | condition is True | |
| 5 | if s[i].isupper(): | condition is True | |
| 6 | L.append(s[i].lower()) | L = ['#', 'l'] | |
| 11 | i += 1 | i = 2 | |
| 4 | while i < len(s): | condition is True | |
| 5 | if s[i].isupper(): | condition is False | |
| 7 | elif s[i].isdigit(): | condition is False | |
| 10 | L.append("#") | L = ['#', 'l', '#'] |
… the same steps continue for the remaining values.
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="@@")
(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.
Write the output of the code.
try:
print('WORD' + '5', end='#')
except TypeError:
print('ERROR', end='#')
finally:
print('OVER')
Output:
WORD5#OVER
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 2 | print('WORD' + '5', end='#') | WORD5# | |
| 6 | print('OVER') | OVER⏎ |
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="#")
(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.
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)
Output:
15$$5 5
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 5 | x = 5 | x = 5 | |
| 6 | change(x) | a = 5, b = 10 | |
| 2 | a = a + b | a = 15 | |
| 3 | b = a - b | b = 5 | |
| 4 | print(a, b, sep="$$") | x = 5 | 15$$5⏎ |
| 7 | print(x) | 5⏎ |
Write the output of the code.
D = {"S01": 45, "S02": 60, "S03": 38}
for k in D:
if D[k] > 40:
print(k, end="#")
Output:
S01#S02#
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {"S01": 45, "S02": 60, "S03": 38} | D = {'S01': 45, 'S02': 60, 'S03': 38} | |
| 2 | for k in D: | k = 'S01' | |
| 3 | if D[k] > 40: | condition is True | |
| 4 | print(k, end="#") | S01# | |
| 2 | for k in D: | k = 'S02' | |
| 3 | if D[k] > 40: | condition is True | |
| 4 | print(k, end="#") | S02# | |
| 2 | for k in D: | k = 'S03' | |
| 3 | if D[k] > 40: | condition is False | |
| 2 | for k in D: | loop ends (no more values) |
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)
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)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 4 | A = [2, 4, 6] | A = [2, 4, 6] | |
| 5 | add(A) | L = [2, 4, 6] | |
| 2 | L.append(L[0] + L[-1]) | L = [2, 4, 6, 8] | |
| 3 | L = [0] | A = [2, 4, 6, 8] | |
| 6 | print(A) | [2, 4, 6, 8]⏎ |
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)
Output:
7202eXAM
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | s = "Exam2027" | s = 'Exam2027' | |
| 2 | t = "" | t = '' | |
| 3 | for ch in s: | ch = 'E' | |
| 4 | if ch.isdigit(): | condition is False | |
| 6 | elif ch.isupper(): | condition is True | |
| 7 | t = t + ch.lower() | t = 'e' | |
| 3 | for ch in s: | ch = 'x' | |
| 4 | if ch.isdigit(): | condition is False | |
| 6 | elif ch.isupper(): | condition is False | |
| 9 | t = t + ch.upper() | t = 'eX' | |
| 3 | for ch in s: | ch = 'a' | |
| 4 | if ch.isdigit(): | condition is False | |
| 6 | elif ch.isupper(): | condition is False | |
| 9 | t = t + ch.upper() | t = 'eXA' | |
| 3 | for ch in s: | ch = 'm' | |
| 4 | if ch.isdigit(): | condition is False |
… the same steps continue for the remaining values.
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))
Output:
7 3 5
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 3 | print(show(1), show(1, z=1), show(y=0, x=5)) | x = 1, y = 2, z = 3 | |
| 2 | return x + y * z | z = 1 | |
| 2 | return x + y * z | x = 5, y = 0, z = 3 | |
| 2 | return x + y * z | 7 3 5⏎ |
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=" ")
a can be 1, 2 or 3. Possible outputs: 20 30 40, 30 40, 40.
Write the output of the code.
x = 10
def f():
global x
x = x + 5
f()
print(x)
Output:
15
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | x = 10 | x = 10 | |
| 4 | x = x + 5 | x = 15 | |
| 6 | print(x) | 15⏎ |
Write the output of the code.
def g(a, b=2):
return a ** b
print(g(3), g(2, 3))
Output:
9 8
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 3 | print(g(3), g(2, 3)) | a = 3, b = 2 | |
| 2 | return a ** b | a = 2, b = 3 | |
| 2 | return a ** b | 9 8⏎ |
Write the output of the code.
L = [1, 2, 3, 4, 5] print(L[::2], L[-2:])
Output:
[1, 3, 5] [4, 5]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [1, 2, 3, 4, 5] | L = [1, 2, 3, 4, 5] | |
| 2 | print(L[::2], L[-2:]) | [1, 3, 5] [4, 5]⏎ |
Write the output of the code.
s = "KVS Delhi" print(s.upper(), s.split()[1][0])
Output:
KVS DELHI D
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | s = "KVS Delhi" | s = 'KVS Delhi' | |
| 2 | print(s.upper(), s.split()[1][0]) | KVS DELHI D⏎ |
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))
Output:
6 3
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {"a": 1, "b": 2, "c": 3} | D = {'a': 1, 'b': 2, 'c': 3} | |
| 2 | t = 0 | t = 0 | |
| 3 | for k in D: | k = 'a' | |
| 4 | t += D[k] | t = 1 | |
| 3 | for k in D: | k = 'b' | |
| 4 | t += D[k] | t = 3 | |
| 3 | for k in D: | k = 'c' | |
| 4 | t += D[k] | t = 6 | |
| 3 | for k in D: | loop ends (no more values) | |
| 5 | print(t, len(D)) | 6 3⏎ |
Write the output of the code.
for i in range(3):
for j in range(i + 1):
print("*", end="")
print()
Output:
* ** ***
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | for i in range(3): | i = 0 | |
| 2 | for j in range(i + 1): | j = 0 | |
| 3 | print("*", end="") | * | |
| 2 | for j in range(i + 1): | loop ends (no more values) | |
| 4 | print() | ⏎ | |
| 1 | for i in range(3): | i = 1 | |
| 2 | for j in range(i + 1): | loop ends (no more values) | |
| 3 | print("*", end="") | * | |
| 2 | for j in range(i + 1): | j = 1 | |
| 3 | print("*", end="") | * | |
| 2 | for j in range(i + 1): | loop ends (no more values) | |
| 4 | print() | ⏎ | |
| 1 | for i in range(3): | i = 2 | |
| 2 | for j in range(i + 1): | j = 0 | |
| 3 | print("*", end="") | * | |
| 2 | for j in range(i + 1): | j = 1 |
… the same steps continue for the remaining values.
Write the output of the code.
n = 4
f = 1
while n > 1:
f *= n
n -= 1
print(f)
Output:
24
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | n = 4 | n = 4 | |
| 2 | f = 1 | f = 1 | |
| 3 | while n > 1: | condition is True | |
| 4 | f *= n | f = 4 | |
| 5 | n -= 1 | n = 3 | |
| 3 | while n > 1: | condition is True | |
| 4 | f *= n | f = 12 | |
| 5 | n -= 1 | n = 2 | |
| 3 | while n > 1: | condition is True | |
| 4 | f *= n | f = 24 | |
| 5 | n -= 1 | n = 1 | |
| 3 | while n > 1: | condition is False | |
| 6 | print(f) | 24⏎ |
Write the output of the code.
L = [3, 6, 9]
for i in range(len(L)):
L[i] = L[i] // 3
print(L)
Output:
[1, 2, 3]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [3, 6, 9] | L = [3, 6, 9] | |
| 2 | for i in range(len(L)): | i = 0 | |
| 3 | L[i] = L[i] // 3 | L = [1, 6, 9] | |
| 2 | for i in range(len(L)): | i = 1 | |
| 3 | L[i] = L[i] // 3 | L = [1, 2, 9] | |
| 2 | for i in range(len(L)): | i = 2 | |
| 3 | L[i] = L[i] // 3 | L = [1, 2, 3] | |
| 2 | for i in range(len(L)): | loop ends (no more values) | |
| 4 | print(L) | [1, 2, 3]⏎ |
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)
Output:
7 4
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 4 | p, q = swap(4, 7) | a = 4, b = 7 | |
| 2 | a, b = b, a | a = 7, b = 4 | |
| 3 | return a, b | p = 7, q = 4 | |
| 5 | print(p, q) | 7 4⏎ |
Write the output of the code.
t = (1, 2, 3) a, b, c = t print(a + c, b * 2)
Output:
4 4
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | t = (1, 2, 3) | t = (1, 2, 3) | |
| 2 | a, b, c = t | a = 1, b = 2, c = 3 | |
| 3 | print(a + c, b * 2) | 4 4⏎ |
Write the output of the code.
s = "abcdef"
r = ""
for ch in s:
if ch in "aeiou":
r += ch.upper()
else:
r += "*"
print(r)
Output:
A***E*
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | s = "abcdef" | s = 'abcdef' | |
| 2 | r = "" | r = '' | |
| 3 | for ch in s: | ch = 'a' | |
| 4 | if ch in "aeiou": | condition is True | |
| 5 | r += ch.upper() | r = 'A' | |
| 3 | for ch in s: | ch = 'b' | |
| 4 | if ch in "aeiou": | condition is False | |
| 7 | r += "*" | r = 'A*' | |
| 3 | for ch in s: | ch = 'c' | |
| 4 | if ch in "aeiou": | condition is False | |
| 7 | r += "*" | r = 'A**' | |
| 3 | for ch in s: | ch = 'd' | |
| 4 | if ch in "aeiou": | condition is False | |
| 7 | r += "*" | r = 'A***' | |
| 3 | for ch in s: | ch = 'e' | |
| 4 | if ch in "aeiou": | condition is True |
… the same steps continue for the remaining values.
Write the output of the code.
try:
n = int("25")
print(n // 0)
except ZeroDivisionError:
print("Zero")
else:
print("OK")
finally:
print("End")
Output:
Zero End
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 2 | n = int("25") | n = 25 | |
| 5 | print("Zero") | Zero⏎ | |
| 9 | print("End") | End⏎ |
Write the output of the code.
try:
L = [1, 2]
print(L[2])
except IndexError:
print("No such index")
Output:
No such index
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 2 | L = [1, 2] | L = [1, 2] | |
| 5 | print("No such index") | No such index⏎ |
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]))
Output:
3
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 7 | print(count([2, 5, 8, 11, 14])) | L = [2, 5, 8, 11, 14] | |
| 2 | c = 0 | c = 0 | |
| 3 | for x in L: | x = 2 | |
| 4 | if x % 2 == 0: | condition is True | |
| 5 | c += 1 | c = 1 | |
| 3 | for x in L: | x = 5 | |
| 4 | if x % 2 == 0: | condition is False | |
| 3 | for x in L: | x = 8 | |
| 4 | if x % 2 == 0: | condition is True | |
| 5 | c += 1 | c = 2 | |
| 3 | for x in L: | x = 11 | |
| 4 | if x % 2 == 0: | condition is False | |
| 3 | for x in L: | x = 14 | |
| 4 | if x % 2 == 0: | condition is True | |
| 5 | c += 1 | c = 3 | |
| 3 | for x in L: | loop ends (no more values) | |
| 6 | return c | 3⏎ |
Write the output of the code.
x = 5
def show():
x = 9
print(x, end=" ")
show()
print(x)
Output:
9 5
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | x = 5 | x = 5 | |
| 3 | x = 9 | x = 9 | |
| 4 | print(x, end=" ") | x = 5 | 9 |
| 6 | print(x) | 5⏎ |
Write the output of the code.
L = ["a", "b"]
M = L
M.append("c")
print(L, len(M))
Output:
['a', 'b', 'c'] 3
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = ["a", "b"] | L = ['a', 'b'] | |
| 2 | M = L | M = ['a', 'b'] | |
| 3 | M.append("c") | L = ['a', 'b', 'c'], M = ['a', 'b', 'c'] | |
| 4 | print(L, len(M)) | ['a', 'b', 'c'] 3⏎ |
Write the output of the code.
D = {}
for w in ["red", "blue", "red"]:
D[w] = D.get(w, 0) + 1
print(D)
Output:
{'red': 2, 'blue': 1}Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {} | D = {} | |
| 2 | for w in ["red", "blue", "red"]: | w = 'red' | |
| 3 | D[w] = D.get(w, 0) + 1 | D = {'red': 1} | |
| 2 | for w in ["red", "blue", "red"]: | w = 'blue' | |
| 3 | D[w] = D.get(w, 0) + 1 | D = {'red': 1, 'blue': 1} | |
| 2 | for w in ["red", "blue", "red"]: | w = 'red' | |
| 3 | D[w] = D.get(w, 0) + 1 | D = {'red': 2, 'blue': 1} | |
| 2 | for w in ["red", "blue", "red"]: | loop ends (no more values) | |
| 4 | print(D) | {'red': 2, 'blue': 1}⏎ |
Write the output of the code.
s = "Python"
print(s[0] + s[-1], s.replace("P", "J"))
Output:
Pn Jython
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | s = "Python" | s = 'Python' | |
| 2 | print(s[0] + s[-1], s.replace("P", "J")) | Pn Jython⏎ |
Write the output of the code.
i = 1
while i < 20:
i *= 3
print(i)
Output:
27
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | i = 1 | i = 1 | |
| 2 | while i < 20: | condition is True | |
| 3 | i *= 3 | i = 3 | |
| 2 | while i < 20: | condition is True | |
| 3 | i *= 3 | i = 9 | |
| 2 | while i < 20: | condition is True | |
| 3 | i *= 3 | i = 27 | |
| 2 | while i < 20: | condition is False | |
| 4 | print(i) | 27⏎ |
Write the output of the code.
L = [10, 20, 30] L.insert(1, 15) L.pop() print(L, sum(L))
Output:
[10, 15, 20] 45
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [10, 20, 30] | L = [10, 20, 30] | |
| 2 | L.insert(1, 15) | L = [10, 15, 20, 30] | |
| 3 | L.pop() | L = [10, 15, 20] | |
| 4 | print(L, sum(L)) | [10, 15, 20] 45⏎ |
Write the output of the code.
def f(n):
if n % 2 == 0:
return "Even"
return "Odd"
print(f(7), f(10))
Output:
Odd Even
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 5 | print(f(7), f(10)) | n = 7 | |
| 2 | if n % 2 == 0: | condition is False | |
| 4 | return "Odd" | n = 10 | |
| 2 | if n % 2 == 0: | condition is True | |
| 3 | return "Even" | Odd Even⏎ |
Write the output of the code.
t = ()
for i in range(1, 4):
t += (i * i,)
print(t)
Output:
(1, 4, 9)
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | t = () | t = () | |
| 2 | for i in range(1, 4): | i = 1 | |
| 3 | t += (i * i,) | t = (1,) | |
| 2 | for i in range(1, 4): | i = 2 | |
| 3 | t += (i * i,) | t = (1, 4) | |
| 2 | for i in range(1, 4): | i = 3 | |
| 3 | t += (i * i,) | t = (1, 4, 9) | |
| 2 | for i in range(1, 4): | loop ends (no more values) | |
| 4 | print(t) | (1, 4, 9)⏎ |
Write the output of the code.
s = "a1b2c3"
d = 0
for ch in s:
if ch.isdigit():
d += int(ch)
print(d)
Output:
6
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | s = "a1b2c3" | s = 'a1b2c3' | |
| 2 | d = 0 | d = 0 | |
| 3 | for ch in s: | ch = 'a' | |
| 4 | if ch.isdigit(): | condition is False | |
| 3 | for ch in s: | ch = '1' | |
| 4 | if ch.isdigit(): | condition is True | |
| 5 | d += int(ch) | d = 1 | |
| 3 | for ch in s: | ch = 'b' | |
| 4 | if ch.isdigit(): | condition is False | |
| 3 | for ch in s: | ch = '2' | |
| 4 | if ch.isdigit(): | condition is True | |
| 5 | d += int(ch) | d = 3 | |
| 3 | for ch in s: | ch = 'c' | |
| 4 | if ch.isdigit(): | condition is False | |
| 3 | for ch in s: | ch = '3' | |
| 4 | if ch.isdigit(): | condition is True |
… the same steps continue for the remaining values.
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))
Output:
9 3
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L = [4, 7, 1, 9] | L = [4, 7, 1, 9] | |
| 2 | m = L[0] | m = 4 | |
| 3 | for x in L: | x = 4 | |
| 4 | if x > m: | condition is False | |
| 3 | for x in L: | x = 7 | |
| 4 | if x > m: | condition is True | |
| 5 | m = x | m = 7 | |
| 3 | for x in L: | x = 1 | |
| 4 | if x > m: | condition is False | |
| 3 | for x in L: | x = 9 | |
| 4 | if x > m: | condition is True | |
| 5 | m = x | m = 9 | |
| 3 | for x in L: | loop ends (no more values) | |
| 6 | print(m, L.index(m)) | 9 3⏎ |
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))
Output:
8 12 12
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 3 | print(add(5), add(5, 5), add(1, c=10)) | a = 5, b = 1, c = 2 | |
| 2 | return a + b + c | b = 5 | |
| 2 | return a + b + c | a = 1, b = 1, c = 10 | |
| 2 | return a + b + c | 8 12 12⏎ |
Write the output of the code.
words = ["sun", "moon", "star"]
for w in words:
print(w[0].upper() + w[1:], end=" ")
Output:
Sun Moon Star
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | words = ["sun", "moon", "star"] | words = ['sun', 'moon', 'star'] | |
| 2 | for w in words: | w = 'sun' | |
| 3 | print(w[0].upper() + w[1:], end=" ") | Sun | |
| 2 | for w in words: | w = 'moon' | |
| 3 | print(w[0].upper() + w[1:], end=" ") | Moon | |
| 2 | for w in words: | w = 'star' | |
| 3 | print(w[0].upper() + w[1:], end=" ") | Star | |
| 2 | for w in words: | loop ends (no more values) |
Write the output of the code.
x = [1, 2, 3] y = x[:] y.append(4) print(len(x), len(y))
Output:
3 4
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | x = [1, 2, 3] | x = [1, 2, 3] | |
| 2 | y = x[:] | y = [1, 2, 3] | |
| 3 | y.append(4) | y = [1, 2, 3, 4] | |
| 4 | print(len(x), len(y)) | 3 4⏎ |
Write the output of the code.
for i in range(5, 0, -2):
print(i, end="-")
Output:
5-3-1-
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | for i in range(5, 0, -2): | i = 5 | |
| 2 | print(i, end="-") | 5- | |
| 1 | for i in range(5, 0, -2): | i = 3 | |
| 2 | print(i, end="-") | 3- | |
| 1 | for i in range(5, 0, -2): | i = 1 | |
| 2 | print(i, end="-") | 1- | |
| 1 | for i in range(5, 0, -2): | loop ends (no more values) |
Write the output of the code.
D = {"x": 1, "y": 2}
D.update({"y": 5, "z": 9})
print(D["y"], sorted(D))
Output:
5 ['x', 'y', 'z']
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | D = {"x": 1, "y": 2} | D = {'x': 1, 'y': 2} | |
| 2 | D.update({"y": 5, "z": 9}) | D = {'x': 1, 'y': 5, 'z': 9} | |
| 3 | print(D["y"], sorted(D)) | 5 ['x', 'y', 'z']⏎ |
Write the output of the code.
n = 1234
r = 0
while n > 0:
r = r * 10 + n % 10
n //= 10
print(r)
Output:
4321
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | n = 1234 | n = 1234 | |
| 2 | r = 0 | r = 0 | |
| 3 | while n > 0: | condition is True | |
| 4 | r = r * 10 + n % 10 | r = 4 | |
| 5 | n //= 10 | n = 123 | |
| 3 | while n > 0: | condition is True | |
| 4 | r = r * 10 + n % 10 | r = 43 | |
| 5 | n //= 10 | n = 12 | |
| 3 | while n > 0: | condition is True | |
| 4 | r = r * 10 + n % 10 | r = 432 | |
| 5 | n //= 10 | n = 1 | |
| 3 | while n > 0: | condition is True | |
| 4 | r = r * 10 + n % 10 | r = 4321 | |
| 5 | n //= 10 | n = 0 | |
| 3 | while n > 0: | condition is False | |
| 6 | print(r) | 4321⏎ |
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)
Output:
[2, 4, 6]
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 4 | A = [1, 2, 3] | A = [1, 2, 3] | |
| 5 | double(A) | L = [1, 2, 3] | |
| 2 | for i in range(len(L)): | i = 0 | |
| 3 | L[i] = L[i] * 2 | L = [2, 2, 3] | |
| 2 | for i in range(len(L)): | i = 1 | |
| 3 | L[i] = L[i] * 2 | L = [2, 4, 3] | |
| 2 | for i in range(len(L)): | i = 2 | |
| 3 | L[i] = L[i] * 2 | L = [2, 4, 6] | |
| 2 | for i in range(len(L)): | A = [2, 4, 6] | |
| 6 | print(A) | [2, 4, 6]⏎ |
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))
Output:
ESBC 4
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | s = "CBSE" | s = 'CBSE' | |
| 2 | for i in range(len(s) - 1, -1, -1): | i = 3 | |
| 3 | print(s[i], end="") | E | |
| 2 | for i in range(len(s) - 1, -1, -1): | i = 2 | |
| 3 | print(s[i], end="") | S | |
| 2 | for i in range(len(s) - 1, -1, -1): | i = 1 | |
| 3 | print(s[i], end="") | B | |
| 2 | for i in range(len(s) - 1, -1, -1): | i = 0 | |
| 3 | print(s[i], end="") | C | |
| 2 | for i in range(len(s) - 1, -1, -1): | loop ends (no more values) | |
| 4 | print() | ⏎ | |
| 5 | print(len(s)) | 4⏎ |
Write the output of the code.
total = 0
for n in [4, 7, 10, 13]:
if n % 2 == 0:
continue
total += n
print(total)
Output:
20
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | total = 0 | total = 0 | |
| 2 | for n in [4, 7, 10, 13]: | n = 4 | |
| 3 | if n % 2 == 0: | condition is True | |
| 2 | for n in [4, 7, 10, 13]: | n = 7 | |
| 3 | if n % 2 == 0: | condition is False | |
| 5 | total += n | total = 7 | |
| 2 | for n in [4, 7, 10, 13]: | n = 10 | |
| 3 | if n % 2 == 0: | condition is True | |
| 2 | for n in [4, 7, 10, 13]: | n = 13 | |
| 3 | if n % 2 == 0: | condition is False | |
| 5 | total += n | total = 20 | |
| 2 | for n in [4, 7, 10, 13]: | loop ends (no more values) | |
| 6 | print(total) | 20⏎ |
Write the output of the code.
def info(name, cls="XII"):
return name + "-" + cls
print(info("Asha"), info("Ravi", "XI"))
Output:
Asha-XII Ravi-XI
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 3 | print(info("Asha"), info("Ravi", "XI")) | name = 'Asha', cls = 'XII' | |
| 2 | return name + "-" + cls | name = 'Ravi', cls = 'XI' | |
| 2 | return name + "-" + cls | Asha-XII Ravi-XI⏎ |
Write MySQL commands to:
SHOW TABLES; DROP DATABASE CS_SP;
Write the command to create the table W_STOCK with columns W_Code (primary key), W_Description, B_Qty and U_Price.
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.
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.
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;
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?
(a) EMPNO, because it identifies every employee uniquely while names can repeat. (b) NOT NULL.
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.
ALTER TABLE EMPLOYEES MODIFY BASICSAL DECIMAL(7,2); DROP TABLE EMPLOYEES;
Write commands to:
USE SHOP; DESC ITEM;
The table ITEM was created without a primary key. Write commands to:
ALTER TABLE ITEM ADD PRIMARY KEY (ICode); ALTER TABLE ITEM DROP PRIMARY KEY;
Write commands to:
INSERT INTO ITEM VALUES (105, 'Pen', 12.5); DELETE FROM ITEM WHERE Price > 500;
Write commands to:
ALTER TABLE MEMBER ADD Phone CHAR(10); ALTER TABLE MEMBER MODIFY MName VARCHAR(40);
Write commands to:
CREATE DATABASE LIBRARY; SHOW DATABASES;
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.
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.
For the table TEACHER (TNo, TName, Subject, Salary, City), write commands to:
ALTER TABLE TEACHER ADD Email VARCHAR(30); ALTER TABLE TEACHER DROP COLUMN City;
For the table TEACHER (TNo, TName, Subject, Salary, City), write commands to:
ALTER TABLE TEACHER MODIFY TName VARCHAR(40); DESC TEACHER;
The table TEACHER (TNo, TName, Subject, Salary, City) was created without a primary key. Write commands to:
ALTER TABLE TEACHER ADD PRIMARY KEY (TNo); INSERT INTO TEACHER VALUES (1, 'Sunita', 'Maths', 52000, 'Delhi');
For the table MOVIE (MNo, Title, Language, Rating, Tickets), write commands to:
ALTER TABLE MOVIE ADD Director VARCHAR(25); ALTER TABLE MOVIE DROP COLUMN Tickets;
For the table MOVIE (MNo, Title, Language, Rating, Tickets), write commands to:
ALTER TABLE MOVIE MODIFY Title VARCHAR(40); DESC MOVIE;
The table MOVIE (MNo, Title, Language, Rating, Tickets) was created without a primary key. Write commands to:
ALTER TABLE MOVIE ADD PRIMARY KEY (MNo); INSERT INTO MOVIE VALUES (1, 'Udaan', 'Hindi', 8, 450);
For the table FLIGHT (FNo, Airline, Source, Seats, Fare), write commands to:
ALTER TABLE FLIGHT ADD Dest VARCHAR(20); ALTER TABLE FLIGHT DROP COLUMN Fare;
For the table FLIGHT (FNo, Airline, Source, Seats, Fare), write commands to:
ALTER TABLE FLIGHT MODIFY FNo VARCHAR(40); DESC FLIGHT;
The table FLIGHT (FNo, Airline, Source, Seats, Fare) was created without a primary key. Write commands to:
ALTER TABLE FLIGHT ADD PRIMARY KEY (FNo);
INSERT INTO FLIGHT VALUES ('F101', 'SkyJet', 'Delhi', 180, 5200);For the table MOBILE (MID, Model, Brand, Price, Stock), write commands to:
ALTER TABLE MOBILE ADD Colour VARCHAR(15); ALTER TABLE MOBILE DROP COLUMN Stock;
For the table MOBILE (MID, Model, Brand, Price, Stock), write commands to:
ALTER TABLE MOBILE MODIFY Model VARCHAR(40); DESC MOBILE;
The table MOBILE (MID, Model, Brand, Price, Stock) was created without a primary key. Write commands to:
ALTER TABLE MOBILE ADD PRIMARY KEY (MID); INSERT INTO MOBILE VALUES (1, 'Nova 5', 'Zen', 12000, 30);
For the table PATIENT (PID, PName, Ward, Days, Bill), write commands to:
ALTER TABLE PATIENT ADD Doctor VARCHAR(25); ALTER TABLE PATIENT DROP COLUMN Bill;
For the table PATIENT (PID, PName, Ward, Days, Bill), write commands to:
ALTER TABLE PATIENT MODIFY PName VARCHAR(40); DESC PATIENT;
The table PATIENT (PID, PName, Ward, Days, Bill) was created without a primary key. Write commands to:
ALTER TABLE PATIENT ADD PRIMARY KEY (PID); INSERT INTO PATIENT VALUES (1, 'Mohan', 'General', 3, 4500);
For the table CLUB (MemNo, MName, Sport, Fee, Age), write commands to:
ALTER TABLE CLUB ADD Phone CHAR(10); ALTER TABLE CLUB DROP COLUMN Age;
For the table CLUB (MemNo, MName, Sport, Fee, Age), write commands to:
ALTER TABLE CLUB MODIFY MName VARCHAR(40); DESC CLUB;
The table CLUB (MemNo, MName, Sport, Fee, Age) was created without a primary key. Write commands to:
ALTER TABLE CLUB ADD PRIMARY KEY (MemNo); INSERT INTO CLUB VALUES (1, 'Arjun', 'Cricket', 1500, 16);
For the table GARMENT (GCode, GName, Size, Price, Qty), write commands to:
ALTER TABLE GARMENT ADD Fabric VARCHAR(15); ALTER TABLE GARMENT DROP COLUMN Qty;
For the table GARMENT (GCode, GName, Size, Price, Qty), write commands to:
ALTER TABLE GARMENT MODIFY GName VARCHAR(40); DESC GARMENT;
The table GARMENT (GCode, GName, Size, Price, Qty) was created without a primary key. Write commands to:
ALTER TABLE GARMENT ADD PRIMARY KEY (GCode);
INSERT INTO GARMENT VALUES ('G1', 'Kurta', 'M', 650, 20);For the table COURSE (CID, CName, Mode, Fees, Seats), write commands to:
ALTER TABLE COURSE ADD Duration INT; ALTER TABLE COURSE DROP COLUMN Seats;
For the table COURSE (CID, CName, Mode, Fees, Seats), write commands to:
ALTER TABLE COURSE MODIFY CName VARCHAR(40); DESC COURSE;
The table COURSE (CID, CName, Mode, Fees, Seats) was created without a primary key. Write commands to:
ALTER TABLE COURSE ADD PRIMARY KEY (CID);
INSERT INTO COURSE VALUES ('C1', 'Python Basics', 'Online', 3000, 60);For the table HOSTEL (RoomNo, SName, Block, Rent, Sem), write commands to:
ALTER TABLE HOSTEL ADD Mess CHAR(3); ALTER TABLE HOSTEL DROP COLUMN Sem;
For the table HOSTEL (RoomNo, SName, Block, Rent, Sem), write commands to:
ALTER TABLE HOSTEL MODIFY SName VARCHAR(40); DESC HOSTEL;
The table HOSTEL (RoomNo, SName, Block, Rent, Sem) was created without a primary key. Write commands to:
ALTER TABLE HOSTEL ADD PRIMARY KEY (RoomNo); INSERT INTO HOSTEL VALUES (101, 'Kiran', 'A', 4000, 1);
For the table BUS (BusNo, Route, Depot, Seats, Fare), write commands to:
ALTER TABLE BUS ADD Driver VARCHAR(25); ALTER TABLE BUS DROP COLUMN Fare;
For the table BUS (BusNo, Route, Depot, Seats, Fare), write commands to:
ALTER TABLE BUS MODIFY Route VARCHAR(40); DESC BUS;
The table BUS (BusNo, Route, Depot, Seats, Fare) was created without a primary key. Write commands to:
ALTER TABLE BUS ADD PRIMARY KEY (BusNo);
INSERT INTO BUS VALUES ('B1', 'Airport Link', 'North', 40, 60);For the table TEACHER (TNo, TName, Subject, Salary, City), write commands to:
DELETE FROM TEACHER WHERE Salary < 45000; DROP TABLE TEACHER;
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'.
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');
For the table MOVIE (MNo, Title, Language, Rating, Tickets), write commands to:
DELETE FROM MOVIE WHERE Tickets < 250; DROP TABLE MOVIE;
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.
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);
For the table FLIGHT (FNo, Airline, Source, Seats, Fare), write commands to:
DELETE FROM FLIGHT WHERE Fare < 4500; DROP TABLE FLIGHT;
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.
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);For the table MOBILE (MID, Model, Brand, Price, Stock), write commands to:
DELETE FROM MOBILE WHERE Price < 10000; DROP TABLE MOBILE;
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.
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);
For the table PATIENT (PID, PName, Ward, Days, Bill), write commands to:
DELETE FROM PATIENT WHERE Bill < 5000; DROP TABLE PATIENT;
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.
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);
For the table CLUB (MemNo, MName, Sport, Fee, Age), write commands to:
DELETE FROM CLUB WHERE Fee < 1000; DROP TABLE CLUB;
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.
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);
For the table GARMENT (GCode, GName, Size, Price, Qty), write commands to:
DELETE FROM GARMENT WHERE Price < 750; DROP TABLE GARMENT;
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.
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);For the table COURSE (CID, CName, Mode, Fees, Seats), write commands to:
DELETE FROM COURSE WHERE Fees < 4000; DROP TABLE COURSE;
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.
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);For the table HOSTEL (RoomNo, SName, Block, Rent, Sem), write commands to:
DELETE FROM HOSTEL WHERE Rent < 4400; DROP TABLE HOSTEL;
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.
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);
For the table BUS (BusNo, Route, Depot, Seats, Fare), write commands to:
DELETE FROM BUS WHERE Fare < 30; DROP TABLE BUS;
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.
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);Name the protocol used to browse web pages. Also name any one web browser.
HTTP (HyperText Transfer Protocol); its secure form is HTTPS. Browsers: Google Chrome, Mozilla Firefox, Microsoft Edge.
Define tree topology. Write one limitation of it.
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.
Write one advantage and one disadvantage of bus topology.
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.
What is a protocol in computer networks? Name the protocol used to transfer hypertext on the web.
A protocol is a set of rules that devices follow to communicate over a network. Hypertext is transferred with HTTP (or HTTPS).
Expand URL and explain it.
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.
Expand PPP and explain it.
Point-to-Point Protocol. It sets up a direct connection between two devices, for example between a computer and an Internet service provider.
Differentiate between a hub and a switch.
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.
Differentiate between LAN and WAN.
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.
Differentiate between circuit switching and packet switching.
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.
Expand SMTP and POP3. Write the use of each.
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.
Differentiate between a web browser and a web server.
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).
Differentiate between HTML and XML.
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.
What is web hosting? What is a domain name? Give one example.
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.
What is a computer network? Write two advantages.
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.
Expand LAN and MAN. Give one example of each.
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.
What is a modem? Why is it needed?
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.
Differentiate between a router and a switch.
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.
What is a gateway?
A gateway is a device that connects two networks that use different protocols. It is the entry and exit point of a network.
What is the role of a repeater? When is it needed?
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.
Write one advantage and one disadvantage of star topology.
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.
Differentiate between bus topology and star topology.
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.
Differentiate between twisted pair cable and optical fibre.
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.
Write two advantages of optical fibre cable.
It has very high speed and bandwidth. It is not affected by electrical or magnetic interference and is secure.
Differentiate between radio waves and infrared waves.
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.
Write one feature and one limitation of microwave communication.
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.
What is bandwidth? In which unit is it measured?
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.
What is data transfer rate? Name two units.
It is the amount of data transferred in one second. Units: bps (bits per second), Kbps, Mbps, Gbps.
Differentiate between an IP address and a MAC address.
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.
Expand TCP/IP. What is its role?
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.
Expand FTP. Write its use.
File Transfer Protocol. It is used to upload and download files between a computer and a server.
Differentiate between HTTP and HTTPS.
HTTP transfers web pages as plain data. HTTPS is the secure form; it encrypts the data, so it is used for banking and payments.
What is TELNET?
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.
Expand VoIP. Write one use.
Voice over Internet Protocol. It carries voice and video calls over the Internet, e.g. video conferencing and Internet calling.
Differentiate between a web page and a website.
A web page is a single document written in HTML. A website is a collection of related web pages under one domain name.
Differentiate between the Internet and the WWW.
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.
What is a URL? Name its parts with an example.
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.
What is a domain name? Give an example.
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.
What is a web server?
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.
What is a web browser? Give two examples.
A web browser is software used to open and view web pages. Examples: Google Chrome, Mozilla Firefox.
Write short notes on ARPANET and NSFNET.
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.
What is packet switching? Write one advantage.
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.
What is a PAN? Give an example.
A PAN (Personal Area Network) connects the devices of one person within a few metres, e.g. a phone connected to a Bluetooth speaker.
What is the function of an Ethernet card? What is RJ45?
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.
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.
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()Write a function that counts how many times the word "Python" occurs in Prog.txt.
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()Write a function that counts the digits present in the text file Space.txt.
def count_digits():
f = open("Space.txt", "r")
c = 0
for ch in f.read():
if ch.isdigit():
c += 1
print(c)
f.close()Write a function that displays the words of Space.txt in which the small letter 'e' occurs at least twice.
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()Write a function that displays the lines of Elections.txt which contain the word "vote".
def show_vote():
f = open("Elections.txt", "r")
for line in f:
if "vote" in line.lower().split():
print(line, end="")
f.close()Write a function that displays the words of Report.txt which start and end with a vowel.
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()Write a function that counts the lines of Story.txt which start with the letter 'T'.
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()Write a function that counts the vowels and the consonants in Poem.txt.
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()Write a function that displays the words of Notes.txt which have more than 5 characters.
def long_words():
f = open("Notes.txt", "r")
for w in f.read().split():
if len(w) > 5:
print(w)
f.close()Write a function that counts the word "the" in Para.txt. Count "The" and "THE" also.
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()Write a function that copies those lines of Old.txt which do not contain the letter 'a' into New.txt.
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()Write a function that displays the number of lines, words and characters in Data.txt.
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))Write a function count_chars() that counts the capital letters in the text file Diary.txt and displays the count.
def count_chars():
f = open("Diary.txt", "r")
c = 0
for ch in f.read():
if ch.isupper():
c += 1
print(c)
f.close()Write a function count_chars() that counts the small letters in the text file Memo.txt and displays the count.
def count_chars():
f = open("Memo.txt", "r")
c = 0
for ch in f.read():
if ch.islower():
c += 1
print(c)
f.close()Write a function count_chars() that counts the spaces in the text file Essay.txt and displays the count.
def count_chars():
f = open("Essay.txt", "r")
c = 0
for ch in f.read():
if ch == " ":
c += 1
print(c)
f.close()Write a function count_chars() that counts the vowels in the text file Speech.txt and displays the count.
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()Write a function count_chars() that counts the letters "a" and "A" in the text file Letter.txt and displays the count.
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()Write a function count_chars() that counts the consonants in the text file Rules.txt and displays the count.
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()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.
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()Write a function count_words() that counts the words that have exactly 4 characters in the text file Blog.txt and displays the count.
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()Write a function count_words() that counts the words that end with "s" in the text file Quote.txt and displays the count.
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()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.
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()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.
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()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.
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()Write a function show_words() that displays the words that have more than 6 characters from the text file Song.txt.
def show_words():
f = open("Song.txt", "r")
for w in f.read().split():
if len(w) > 6:
print(w, end=" ")
f.close()Write a function show_words() that displays the words that start with a vowel from the text file Tale.txt.
def show_words():
f = open("Tale.txt", "r")
for w in f.read().split():
if w[0] in "aeiouAEIOU":
print(w, end=" ")
f.close()Write a function show_words() that displays the words written fully in capital letters from the text file Riddle.txt.
def show_words():
f = open("Riddle.txt", "r")
for w in f.read().split():
if w.isupper():
print(w, end=" ")
f.close()Write a function show_words() that displays the words that start and end with the same letter from the text file Chapter.txt.
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()Write a function show_words() that displays the words that contain the letter "e" exactly once from the text file Recipe.txt.
def show_words():
f = open("Recipe.txt", "r")
for w in f.read().split():
if w.count("e") == 1:
print(w, end=" ")
f.close()Write a function show_words() that displays the words that have fewer than 3 characters from the text file Motto.txt.
def show_words():
f = open("Motto.txt", "r")
for w in f.read().split():
if len(w) < 3:
print(w, end=" ")
f.close()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.
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()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.
def count_lines():
f = open("Summary.txt", "r")
c = 0
for line in f:
if line.strip().endswith("."):
c += 1
print(c)
f.close()Write a function count_lines() that counts the lines that contain the word "the" in the text file Agenda.txt and displays the count.
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()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.
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()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.
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()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.
def count_lines():
f = open("Verse.txt", "r")
c = 0
for line in f:
if line[0].isupper():
c += 1
print(c)
f.close()Write a function show_lines() that displays the lines that contain the word "Python" from the text file Journal.txt.
def show_lines():
f = open("Journal.txt", "r")
for line in f:
if "Python" in line:
print(line, end="")
f.close()Write a function show_lines() that displays the lines that start with "T" from the text file Travel.txt.
def show_lines():
f = open("Travel.txt", "r")
for line in f:
if line[0] == "T":
print(line, end="")
f.close()Write a function show_lines() that displays the lines that contain a comma from the text file Science.txt.
def show_lines():
f = open("Science.txt", "r")
for line in f:
if "," in line:
print(line, end="")
f.close()Write a function show_lines() that displays the lines that have exactly 6 words from the text file Timeline.txt.
def show_lines():
f = open("Timeline.txt", "r")
for line in f:
if len(line.split()) == 6:
print(line, end="")
f.close()Write a function show_lines() that displays the lines that do not contain the letter "i" from the text file Facts.txt.
def show_lines():
f = open("Facts.txt", "r")
for line in f:
if "i" not in line:
print(line, end="")
f.close()Write a function show_lines() that displays the lines whose first word has more than 3 letters from the text file Message.txt.
def show_lines():
f = open("Message.txt", "r")
for line in f:
if len(line.split()[0]) > 3:
print(line, end="")
f.close()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".
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")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.
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=" ")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.
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()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".
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=" ")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.)
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])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.
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")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.
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=" ")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.
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()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.
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])Write a function reverse(s) that uses a stack to return the reverse of the string s.
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
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.
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])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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())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".
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")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.
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())Write a function avg_len() that adds the lengths of all the words of the list my_words and prints the average word length.
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
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.
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
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.)
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']
Write a function sum_positive(list1) that prints the sum of the positive numbers of the list. (2 marks in the sample paper.)
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
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)
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)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | L1 = [] | L1 = [] | |
| 2 | L2 = [] | L2 = [] | |
| 7 | D = {1: "ONE", 2: "TWO", 3: "THREE"} | D = {1: 'ONE', 2: 'TWO', 3: 'THREE'} | |
| 4 | for k in D: | k = 1 | |
| 4 | for k in D: | k = 2 | |
| 4 | for k in D: | k = 3 | |
| 4 | for k in D: | L1 = [1, 2, 3], L2 = ['ONE', 'TWO', 'THREE'] | |
| 9 | print(L1) | [1, 2, 3]⏎ | |
| 10 | print(L2) | ['ONE', 'TWO', 'THREE']⏎ | |
| 11 | print(D) | {1: 'ONE', 2: 'TWO', 3: 'THREE'}⏎ |
Write a function count_upper(s) that returns the number of capital letters in the string s.
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
Write a function odd_squares(L) that returns a new list with the squares of the odd numbers of L.
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]
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"))
Output:
B1A3D
Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 10 | print(modify("board")) | s = 'board' | |
| 2 | r = "" | r = '' | |
| 3 | for i in range(len(s)): | i = 0 | |
| 4 | if i % 2 == 0: | condition is True | |
| 5 | r += s[i].upper() | r = 'B' | |
| 3 | for i in range(len(s)): | i = 1 | |
| 4 | if i % 2 == 0: | condition is False | |
| 7 | r += str(i) | r = 'B1' | |
| 3 | for i in range(len(s)): | i = 2 | |
| 4 | if i % 2 == 0: | condition is True | |
| 5 | r += s[i].upper() | r = 'B1A' | |
| 3 | for i in range(len(s)): | i = 3 | |
| 4 | if i % 2 == 0: | condition is False | |
| 7 | r += str(i) | r = 'B1A3' | |
| 3 | for i in range(len(s)): | i = 4 | |
| 4 | if i % 2 == 0: | condition is True |
… the same steps continue for the remaining values.
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)
Output:
{0: 6, 1: 4, 2: 10, 3: 6}Working (step by step)
| Line | Statement | Values after this step | Printed |
|---|---|---|---|
| 1 | T = (3, 8, 5, 12) | T = (3, 8, 5, 12) | |
| 2 | D = {} | D = {} | |
| 3 | for i in range(len(T)): | i = 0 | |
| 4 | if T[i] % 2 == 0: | condition is False | |
| 7 | D[i] = T[i] * 2 | D = {0: 6} | |
| 3 | for i in range(len(T)): | i = 1 | |
| 4 | if T[i] % 2 == 0: | condition is True | |
| 5 | D[i] = T[i] // 2 | D = {0: 6, 1: 4} | |
| 3 | for i in range(len(T)): | i = 2 | |
| 4 | if T[i] % 2 == 0: | condition is False | |
| 7 | D[i] = T[i] * 2 | D = {0: 6, 1: 4, 2: 10} | |
| 3 | for i in range(len(T)): | i = 3 | |
| 4 | if T[i] % 2 == 0: | condition is True | |
| 5 | D[i] = T[i] // 2 | D = {0: 6, 1: 4, 2: 10, 3: 6} | |
| 3 | for i in range(len(T)): | loop ends (no more values) | |
| 8 | print(D) | {0: 6, 1: 4, 2: 10, 3: 6}⏎ |
Write a function is_prime(n) that returns True if n is a prime number, otherwise False.
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
Write a function longest(sentence) that returns the longest word of a sentence.
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
Write a function vowel_count(s) that returns a dictionary showing how many times each vowel occurs in s.
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}Write a function total(L) that returns the sum of the elements of a list without using sum().
def total(L):
s = 0
for x in L:
s += x
return s
print(total([4, 8, 15]))Output:
27
Write a function count_vowels(s) that returns the number of vowels in a string.
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
Write a function reverse_words(s) that returns the sentence with its words in reverse order.
def reverse_words(s):
words = s.split()
words.reverse()
return " ".join(words)
print(reverse_words("Python is easy"))Output:
easy is Python
Write a function evens(L) that returns a list of the even numbers of 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]
Write a function largest(a, b, c) that returns the largest of three numbers without using max().
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
Write a function fact(n) that returns the factorial of n.
def fact(n):
f = 1
for i in range(1, n + 1):
f *= i
return f
print(fact(6))Output:
720
Write a function table(n) that prints the first five multiples of n on one line.
def table(n):
for i in range(1, 6):
print(n * i, end=" ")
table(7)Output:
7 14 21 28 35
Write a function count_word(s, w) that returns how many times the word w occurs in the sentence s.
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
Write a function swap_case(s) that changes capital letters to small and small letters to capital, without using swapcase().
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
Write a function second_largest(L) that returns the second largest number of a list of different numbers.
def second_largest(L):
M = sorted(L)
return M[-2]
print(second_largest([14, 67, 29, 51]))Output:
51
Write a function remove_dup(L) that returns a list without repeated elements, keeping the first occurrence.
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]
Write a function sum_digits(n) that returns the sum of the digits of a number.
def sum_digits(n):
s = 0
while n > 0:
s += n % 10
n //= 10
return s
print(sum_digits(4725))Output:
18
Write a function fib(n) that prints the first n numbers of the Fibonacci series.
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
Write a function count_range(L, lo, hi) that returns how many numbers of L lie from lo to hi (both included).
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
Write a function invert(D) that returns a new dictionary in which the keys and values of D are exchanged.
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'}Write a function initials(name) that returns the first letters of all the words of a name in capitals.
def initials(name):
r = ""
for w in name.split():
r += w[0].upper()
return r
print(initials("kendriya vidyalaya sangathan"))Output:
KVS
Write a function average(T) that returns the average of the numbers of a tuple.
def average(T):
s = 0
for x in T:
s += x
return s / len(T)
print(average((10, 20, 60)))Output:
30.0
Write a function power(b, e) that returns b raised to e using a loop.
def power(b, e):
p = 1
for i in range(e):
p *= b
return p
print(power(2, 10))Output:
1024
Write a function positions(L, x) that returns a list of the indexes at which x occurs in 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]
Write a function hcf(a, b) that returns the highest common factor of two numbers.
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
Write a function count_types(s) that returns two values: the number of letters and the number of digits in s.
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)
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.
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']
Write a function shift_left(L) that moves the first element of the list to the end.
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]
Write a function to_dict(K, V) that makes a dictionary from a list of keys and a list of values.
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}Write a function grade(m) that returns "A" for marks 75 or more, "B" for 50 or more, otherwise "C".
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
Write a function min_max(L) that returns both the smallest and the largest number of a list.
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)
Write a function interest(p, r=5, t=1) that returns the simple interest. Call it with one, two and three arguments.
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
Write a function squares(n) that returns a dictionary of the numbers 1 to n with their squares.
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}Write a function is_leap(y) that returns True if y is a leap year.
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
Write a function count_long(L, n) that returns how many strings of the list L have more than n characters.
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
Write a function count_even(T) that returns how many numbers of a tuple are even.
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
Write a function first_last(s) that returns a string made of the first and the last character of every word of s.
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
Write a function multiples(n, k) that returns a list of the first k multiples of n.
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]
Table TECH_EVENT_REG is given below. Write queries to:
Table: TECH_EVENT_REG
| reg_id | participant_name | event_name | grade | reg_fee |
|---|---|---|---|---|
| 501 | Aarav | Hackathon | 11 | 200 |
| 502 | Riya | RoboRace | 10 | 150 |
| 503 | Krish | WebDev Challenge | 12 | 250 |
| 504 | Navya | Hackathon | 11 | 200 |
| 505 | Samaira | CodeSprint | 9 | 100 |
| 506 | Rohan | RoboRace | 10 | 150 |
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;
Write the output of these queries on the table TECH_EVENT_REG of the sample paper.
Table: TECH_EVENT_REG
| reg_id | participant_name | event_name | grade | reg_fee |
|---|---|---|---|---|
| 501 | Aarav | Hackathon | 11 | 200 |
| 502 | Riya | RoboRace | 10 | 150 |
| 503 | Krish | WebDev Challenge | 12 | 250 |
| 504 | Navya | Hackathon | 11 | 200 |
| 505 | Samaira | CodeSprint | 9 | 100 |
| 506 | Rohan | RoboRace | 10 | 150 |
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;
| participant_name | event_name |
|---|---|
| Aarav | Hackathon |
| Navya | Hackathon |
Explanation: WHERE keeps only the rows where grade is 11: 2 of the 6 rows match (Aarav, Navya).
| event_name | COUNT(*) |
|---|---|
| CodeSprint | 1 |
| Hackathon | 2 |
| RoboRace | 2 |
| WebDev Challenge | 1 |
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.
| participant_name |
|---|
| Krish |
Explanation: WHERE keeps only the rows where reg_fee is more than 200: 1 of the 6 rows matches (Krish).
| 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.
Table STOCK (Code, Type, Qty, Price ...). Write queries to:
Table: STOCK
| Code | Type | Qty | Price |
|---|---|---|---|
| Columns only. The rows are given in the question paper. | |||
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%';
Table WORKER (WNAME, WAGE, HOURS, TYPE, SITEID ...). Write queries to:
Table: WORKER
| WNAME | WAGE | HOURS | TYPE | SITEID |
|---|---|---|---|---|
| Columns only. The rows are given in the question paper. | ||||
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';
Table STUDENT (RNo, Name, Stream, Marks, City). Write queries to:
Table: STUDENT
| RNo | Name | Stream | Marks | City |
|---|---|---|---|---|
| Columns only. The rows are given in the question paper. | ||||
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';
Table EMPLOYEE (ENo, EName, Dept, Salary, DOJ). Write queries to:
Table: EMPLOYEE
| ENo | EName | Dept | Salary | DOJ |
|---|---|---|---|---|
| Columns only. The rows are given in the question paper. | ||||
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;
Table BOOK (BNo, Title, Author, Price, Qty). Write queries to:
Table: BOOK
| BNo | Title | Author | Price | Qty |
|---|---|---|---|---|
| Columns only. The rows are given in the question paper. | ||||
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';
Table PRODUCT (PID, PName, Company, Price, Stock). Write queries to:
Table: PRODUCT
| PID | PName | Company | Price | Stock |
|---|---|---|---|---|
| Columns only. The rows are given in the question paper. | ||||
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);
Table DOCTOR (DID, DName, Dept, Fee, Experience). Write queries to:
Table: DOCTOR
| DID | DName | Dept | Fee | Experience |
|---|---|---|---|---|
| Columns only. The rows are given in the question paper. | ||||
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;Table TRAIN (TNo, TName, Source, Dest, Fare). Write queries to:
Table: TRAIN
| TNo | TName | Source | Dest | Fare |
|---|---|---|---|---|
| Columns only. The rows are given in the question paper. | ||||
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';
Write SQL queries for the following, based on the table TEACHER.
Table: TEACHER
| TNo | TName | Subject | Salary | City |
|---|---|---|---|---|
| 1 | Sunita | Maths | 52000 | Delhi |
| 2 | Rakesh | Physics | 61000 | Agra |
| 3 | Seema | Maths | 48000 | Delhi |
| 4 | Imran | English | 45000 | Pune |
| 5 | Suresh | Physics | 58000 | Delhi |
| 6 | Anita | English | 39000 | Agra |
SELECT TName, Salary FROM TEACHER WHERE City = 'Delhi';
| TName | Salary |
|---|---|
| Sunita | 52000 |
| Seema | 48000 |
| Suresh | 58000 |
Explanation: WHERE keeps only the rows where City is 'Delhi': 3 of the 6 rows match (Sunita, Seema, Suresh).
SELECT Subject, COUNT(*) FROM TEACHER GROUP BY Subject;
| Subject | COUNT(*) |
|---|---|
| English | 2 |
| Maths | 2 |
| Physics | 2 |
Explanation: GROUP BY Subject makes 3 groups (English, Maths, Physics); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.
SELECT * FROM TEACHER WHERE Salary BETWEEN 45000 AND 58000;
| TNo | TName | Subject | Salary | City |
|---|---|---|---|---|
| 1 | Sunita | Maths | 52000 | Delhi |
| 3 | Seema | Maths | 48000 | Delhi |
| 4 | Imran | English | 45000 | Pune |
| 5 | Suresh | Physics | 58000 | Delhi |
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).
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.
Write SQL queries for the following, based on the table TEACHER.
Table: TEACHER
| TNo | TName | Subject | Salary | City |
|---|---|---|---|---|
| 1 | Sunita | Maths | 52000 | Delhi |
| 2 | Rakesh | Physics | 61000 | Agra |
| 3 | Seema | Maths | 48000 | Delhi |
| 4 | Imran | English | 45000 | Pune |
| 5 | Suresh | Physics | 58000 | Delhi |
| 6 | Anita | English | 39000 | Agra |
SELECT * FROM TEACHER ORDER BY Salary DESC;
| TNo | TName | Subject | Salary | City |
|---|---|---|---|---|
| 2 | Rakesh | Physics | 61000 | Agra |
| 5 | Suresh | Physics | 58000 | Delhi |
| 1 | Sunita | Maths | 52000 | Delhi |
| 3 | Seema | Maths | 48000 | Delhi |
| 4 | Imran | English | 45000 | Pune |
| 6 | Anita | English | 39000 | Agra |
Explanation: ORDER BY Salary arranges the result in descending (largest first) order.
SELECT MAX(Salary), MIN(Salary) FROM TEACHER;
| MAX(Salary) | MIN(Salary) |
|---|---|
| 61000 | 39000 |
Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.
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'.
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.
Write SQL queries for the following, based on the table TEACHER.
Table: TEACHER
| TNo | TName | Subject | Salary | City |
|---|---|---|---|---|
| 1 | Sunita | Maths | 52000 | Delhi |
| 2 | Rakesh | Physics | 61000 | Agra |
| 3 | Seema | Maths | 48000 | Delhi |
| 4 | Imran | English | 45000 | Pune |
| 5 | Suresh | Physics | 58000 | Delhi |
| 6 | Anita | English | 39000 | Agra |
SELECT DISTINCT Subject FROM TEACHER;
| Subject |
|---|
| Maths |
| Physics |
| English |
Explanation: DISTINCT removes the repeated rows from the result of all the rows.
SELECT Subject, COUNT(*) FROM TEACHER GROUP BY Subject HAVING COUNT(*) > 1;
| Subject | COUNT(*) |
|---|---|
| English | 2 |
| Maths | 2 |
| Physics | 2 |
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.
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).
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.
Write SQL queries for the following, based on the table MOVIE.
Table: MOVIE
| MNo | Title | Language | Rating | Tickets |
|---|---|---|---|---|
| 1 | Udaan | Hindi | 8 | 450 |
| 2 | Sagar | Tamil | 7 | 300 |
| 3 | Safar | Hindi | 6 | 520 |
| 4 | Nadi | Bengali | 9 | 210 |
| 5 | Sapna | Tamil | 8 | 390 |
| 6 | Dhoop | Hindi | 5 | 150 |
SELECT Title, Tickets FROM MOVIE WHERE Language = 'Hindi';
| Title | Tickets |
|---|---|
| Udaan | 450 |
| Safar | 520 |
| Dhoop | 150 |
Explanation: WHERE keeps only the rows where Language is 'Hindi': 3 of the 6 rows match (Udaan, Safar, Dhoop).
SELECT Language, COUNT(*) FROM MOVIE GROUP BY Language;
| Language | COUNT(*) |
|---|---|
| Bengali | 1 |
| Hindi | 3 |
| Tamil | 2 |
Explanation: GROUP BY Language makes 3 groups (Bengali, Hindi, Tamil); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.
SELECT * FROM MOVIE WHERE Tickets BETWEEN 200 AND 400;
| MNo | Title | Language | Rating | Tickets |
|---|---|---|---|---|
| 2 | Sagar | Tamil | 7 | 300 |
| 4 | Nadi | Bengali | 9 | 210 |
| 5 | Sapna | Tamil | 8 | 390 |
Explanation: WHERE keeps only the rows where Tickets is from 200 to 400 (both included): 3 of the 6 rows match (Sagar, Nadi, Sapna).
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.
Write SQL queries for the following, based on the table MOVIE.
Table: MOVIE
| MNo | Title | Language | Rating | Tickets |
|---|---|---|---|---|
| 1 | Udaan | Hindi | 8 | 450 |
| 2 | Sagar | Tamil | 7 | 300 |
| 3 | Safar | Hindi | 6 | 520 |
| 4 | Nadi | Bengali | 9 | 210 |
| 5 | Sapna | Tamil | 8 | 390 |
| 6 | Dhoop | Hindi | 5 | 150 |
SELECT * FROM MOVIE ORDER BY Tickets DESC;
| MNo | Title | Language | Rating | Tickets |
|---|---|---|---|---|
| 3 | Safar | Hindi | 6 | 520 |
| 1 | Udaan | Hindi | 8 | 450 |
| 5 | Sapna | Tamil | 8 | 390 |
| 2 | Sagar | Tamil | 7 | 300 |
| 4 | Nadi | Bengali | 9 | 210 |
| 6 | Dhoop | Hindi | 5 | 150 |
Explanation: ORDER BY Tickets arranges the result in descending (largest first) order.
SELECT MAX(Tickets), MIN(Tickets) FROM MOVIE;
| MAX(Tickets) | MIN(Tickets) |
|---|---|
| 520 | 150 |
Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.
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'.
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.
Write SQL queries for the following, based on the table MOVIE.
Table: MOVIE
| MNo | Title | Language | Rating | Tickets |
|---|---|---|---|---|
| 1 | Udaan | Hindi | 8 | 450 |
| 2 | Sagar | Tamil | 7 | 300 |
| 3 | Safar | Hindi | 6 | 520 |
| 4 | Nadi | Bengali | 9 | 210 |
| 5 | Sapna | Tamil | 8 | 390 |
| 6 | Dhoop | Hindi | 5 | 150 |
SELECT DISTINCT Language FROM MOVIE;
| Language |
|---|
| Hindi |
| Tamil |
| Bengali |
Explanation: DISTINCT removes the repeated rows from the result of all the rows.
SELECT Language, COUNT(*) FROM MOVIE GROUP BY Language HAVING COUNT(*) > 1;
| Language | COUNT(*) |
|---|---|
| Hindi | 3 |
| Tamil | 2 |
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.
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).
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.
Write SQL queries for the following, based on the table FLIGHT.
Table: FLIGHT
| FNo | Airline | Source | Seats | Fare |
|---|---|---|---|---|
| F101 | SkyJet | Delhi | 180 | 5200 |
| F102 | AirWing | Mumbai | 150 | 4800 |
| F103 | SkyJet | Delhi | 200 | 6100 |
| F104 | CloudAir | Kolkata | 120 | 3900 |
| F105 | AirWing | Delhi | 160 | 5500 |
| F106 | CloudAir | Mumbai | 140 | 4200 |
SELECT FNo, Fare FROM FLIGHT WHERE Source = 'Delhi';
| FNo | Fare |
|---|---|
| F101 | 5200 |
| F103 | 6100 |
| F105 | 5500 |
Explanation: WHERE keeps only the rows where Source is 'Delhi': 3 of the 6 rows match (F101, F103, F105).
SELECT Airline, COUNT(*) FROM FLIGHT GROUP BY Airline;
| Airline | COUNT(*) |
|---|---|
| AirWing | 2 |
| CloudAir | 2 |
| SkyJet | 2 |
Explanation: GROUP BY Airline makes 3 groups (AirWing, CloudAir, SkyJet); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.
SELECT * FROM FLIGHT WHERE Fare BETWEEN 4000 AND 5500;
| FNo | Airline | Source | Seats | Fare |
|---|---|---|---|---|
| F101 | SkyJet | Delhi | 180 | 5200 |
| F102 | AirWing | Mumbai | 150 | 4800 |
| F105 | AirWing | Delhi | 160 | 5500 |
| F106 | CloudAir | Mumbai | 140 | 4200 |
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).
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.
Write SQL queries for the following, based on the table FLIGHT.
Table: FLIGHT
| FNo | Airline | Source | Seats | Fare |
|---|---|---|---|---|
| F101 | SkyJet | Delhi | 180 | 5200 |
| F102 | AirWing | Mumbai | 150 | 4800 |
| F103 | SkyJet | Delhi | 200 | 6100 |
| F104 | CloudAir | Kolkata | 120 | 3900 |
| F105 | AirWing | Delhi | 160 | 5500 |
| F106 | CloudAir | Mumbai | 140 | 4200 |
SELECT * FROM FLIGHT ORDER BY Fare DESC;
| FNo | Airline | Source | Seats | Fare |
|---|---|---|---|---|
| F103 | SkyJet | Delhi | 200 | 6100 |
| F105 | AirWing | Delhi | 160 | 5500 |
| F101 | SkyJet | Delhi | 180 | 5200 |
| F102 | AirWing | Mumbai | 150 | 4800 |
| F106 | CloudAir | Mumbai | 140 | 4200 |
| F104 | CloudAir | Kolkata | 120 | 3900 |
Explanation: ORDER BY Fare arranges the result in descending (largest first) order.
SELECT MAX(Fare), MIN(Fare) FROM FLIGHT;
| MAX(Fare) | MIN(Fare) |
|---|---|
| 6100 | 3900 |
Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.
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'.
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.
Write SQL queries for the following, based on the table FLIGHT.
Table: FLIGHT
| FNo | Airline | Source | Seats | Fare |
|---|---|---|---|---|
| F101 | SkyJet | Delhi | 180 | 5200 |
| F102 | AirWing | Mumbai | 150 | 4800 |
| F103 | SkyJet | Delhi | 200 | 6100 |
| F104 | CloudAir | Kolkata | 120 | 3900 |
| F105 | AirWing | Delhi | 160 | 5500 |
| F106 | CloudAir | Mumbai | 140 | 4200 |
SELECT DISTINCT Airline FROM FLIGHT;
| Airline |
|---|
| SkyJet |
| AirWing |
| CloudAir |
Explanation: DISTINCT removes the repeated rows from the result of all the rows.
SELECT Airline, COUNT(*) FROM FLIGHT GROUP BY Airline HAVING COUNT(*) > 1;
| Airline | COUNT(*) |
|---|---|
| AirWing | 2 |
| CloudAir | 2 |
| SkyJet | 2 |
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.
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).
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.
Write SQL queries for the following, based on the table MOBILE.
Table: MOBILE
| MID | Model | Brand | Price | Stock |
|---|---|---|---|---|
| 1 | Nova 5 | Zen | 12000 | 30 |
| 2 | Alpha X | Orbit | 18500 | 12 |
| 3 | Nova 7 | Zen | 15500 | 8 |
| 4 | Pixel Go | Lumo | 9900 | 45 |
| 5 | Alpha Z | Orbit | 22000 | 5 |
| 6 | Lite 2 | Lumo | 7500 | 60 |
SELECT Model, Price FROM MOBILE WHERE Brand = 'Zen';
| Model | Price |
|---|---|
| Nova 5 | 12000 |
| Nova 7 | 15500 |
Explanation: WHERE keeps only the rows where Brand is 'Zen': 2 of the 6 rows match (Nova 5, Nova 7).
SELECT Brand, COUNT(*) FROM MOBILE GROUP BY Brand;
| Brand | COUNT(*) |
|---|---|
| Lumo | 2 |
| Orbit | 2 |
| Zen | 2 |
Explanation: GROUP BY Brand makes 3 groups (Lumo, Orbit, Zen); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.
SELECT * FROM MOBILE WHERE Price BETWEEN 9000 AND 16000;
| MID | Model | Brand | Price | Stock |
|---|---|---|---|---|
| 1 | Nova 5 | Zen | 12000 | 30 |
| 3 | Nova 7 | Zen | 15500 | 8 |
| 4 | Pixel Go | Lumo | 9900 | 45 |
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).
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.
Write SQL queries for the following, based on the table MOBILE.
Table: MOBILE
| MID | Model | Brand | Price | Stock |
|---|---|---|---|---|
| 1 | Nova 5 | Zen | 12000 | 30 |
| 2 | Alpha X | Orbit | 18500 | 12 |
| 3 | Nova 7 | Zen | 15500 | 8 |
| 4 | Pixel Go | Lumo | 9900 | 45 |
| 5 | Alpha Z | Orbit | 22000 | 5 |
| 6 | Lite 2 | Lumo | 7500 | 60 |
SELECT * FROM MOBILE ORDER BY Price DESC;
| MID | Model | Brand | Price | Stock |
|---|---|---|---|---|
| 5 | Alpha Z | Orbit | 22000 | 5 |
| 2 | Alpha X | Orbit | 18500 | 12 |
| 3 | Nova 7 | Zen | 15500 | 8 |
| 1 | Nova 5 | Zen | 12000 | 30 |
| 4 | Pixel Go | Lumo | 9900 | 45 |
| 6 | Lite 2 | Lumo | 7500 | 60 |
Explanation: ORDER BY Price arranges the result in descending (largest first) order.
SELECT MAX(Price), MIN(Price) FROM MOBILE;
| MAX(Price) | MIN(Price) |
|---|---|
| 22000 | 7500 |
Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.
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'.
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.
Write SQL queries for the following, based on the table MOBILE.
Table: MOBILE
| MID | Model | Brand | Price | Stock |
|---|---|---|---|---|
| 1 | Nova 5 | Zen | 12000 | 30 |
| 2 | Alpha X | Orbit | 18500 | 12 |
| 3 | Nova 7 | Zen | 15500 | 8 |
| 4 | Pixel Go | Lumo | 9900 | 45 |
| 5 | Alpha Z | Orbit | 22000 | 5 |
| 6 | Lite 2 | Lumo | 7500 | 60 |
SELECT DISTINCT Brand FROM MOBILE;
| Brand |
|---|
| Zen |
| Orbit |
| Lumo |
Explanation: DISTINCT removes the repeated rows from the result of all the rows.
SELECT Brand, COUNT(*) FROM MOBILE GROUP BY Brand HAVING COUNT(*) > 1;
| Brand | COUNT(*) |
|---|---|
| Lumo | 2 |
| Orbit | 2 |
| Zen | 2 |
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.
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).
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.
Write SQL queries for the following, based on the table PATIENT.
Table: PATIENT
| PID | PName | Ward | Days | Bill |
|---|---|---|---|---|
| 1 | Mohan | General | 3 | 4500 |
| 2 | Rekha | ICU | 5 | 32000 |
| 3 | Manoj | General | 2 | 2800 |
| 4 | Farah | Private | 4 | 18000 |
| 5 | Meena | ICU | 2 | 15000 |
| 6 | Gopal | Private | 6 | 27000 |
SELECT PName, Bill FROM PATIENT WHERE Ward = 'ICU';
| PName | Bill |
|---|---|
| Rekha | 32000 |
| Meena | 15000 |
Explanation: WHERE keeps only the rows where Ward is 'ICU': 2 of the 6 rows match (Rekha, Meena).
SELECT Ward, COUNT(*) FROM PATIENT GROUP BY Ward;
| Ward | COUNT(*) |
|---|---|
| General | 2 |
| ICU | 2 |
| Private | 2 |
Explanation: GROUP BY Ward makes 3 groups (General, ICU, Private); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.
SELECT * FROM PATIENT WHERE Bill BETWEEN 4000 AND 20000;
| PID | PName | Ward | Days | Bill |
|---|---|---|---|---|
| 1 | Mohan | General | 3 | 4500 |
| 4 | Farah | Private | 4 | 18000 |
| 5 | Meena | ICU | 2 | 15000 |
Explanation: WHERE keeps only the rows where Bill is from 4000 to 20000 (both included): 3 of the 6 rows match (Mohan, Farah, Meena).
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.
Write SQL queries for the following, based on the table PATIENT.
Table: PATIENT
| PID | PName | Ward | Days | Bill |
|---|---|---|---|---|
| 1 | Mohan | General | 3 | 4500 |
| 2 | Rekha | ICU | 5 | 32000 |
| 3 | Manoj | General | 2 | 2800 |
| 4 | Farah | Private | 4 | 18000 |
| 5 | Meena | ICU | 2 | 15000 |
| 6 | Gopal | Private | 6 | 27000 |
SELECT * FROM PATIENT ORDER BY Bill DESC;
| PID | PName | Ward | Days | Bill |
|---|---|---|---|---|
| 2 | Rekha | ICU | 5 | 32000 |
| 6 | Gopal | Private | 6 | 27000 |
| 4 | Farah | Private | 4 | 18000 |
| 5 | Meena | ICU | 2 | 15000 |
| 1 | Mohan | General | 3 | 4500 |
| 3 | Manoj | General | 2 | 2800 |
Explanation: ORDER BY Bill arranges the result in descending (largest first) order.
SELECT MAX(Bill), MIN(Bill) FROM PATIENT;
| MAX(Bill) | MIN(Bill) |
|---|---|
| 32000 | 2800 |
Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.
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'.
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.
Write SQL queries for the following, based on the table PATIENT.
Table: PATIENT
| PID | PName | Ward | Days | Bill |
|---|---|---|---|---|
| 1 | Mohan | General | 3 | 4500 |
| 2 | Rekha | ICU | 5 | 32000 |
| 3 | Manoj | General | 2 | 2800 |
| 4 | Farah | Private | 4 | 18000 |
| 5 | Meena | ICU | 2 | 15000 |
| 6 | Gopal | Private | 6 | 27000 |
SELECT DISTINCT Ward FROM PATIENT;
| Ward |
|---|
| General |
| ICU |
| Private |
Explanation: DISTINCT removes the repeated rows from the result of all the rows.
SELECT Ward, COUNT(*) FROM PATIENT GROUP BY Ward HAVING COUNT(*) > 1;
| Ward | COUNT(*) |
|---|---|
| General | 2 |
| ICU | 2 |
| Private | 2 |
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.
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).
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.
Write SQL queries for the following, based on the table CLUB.
Table: CLUB
| MemNo | MName | Sport | Fee | Age |
|---|---|---|---|---|
| 1 | Arjun | Cricket | 1500 | 16 |
| 2 | Nisha | Tennis | 2200 | 15 |
| 3 | Aman | Cricket | 1500 | 17 |
| 4 | Pooja | Chess | 800 | 14 |
| 5 | Ankit | Tennis | 2200 | 16 |
| 6 | Ritu | Chess | 800 | 15 |
SELECT MName, Fee FROM CLUB WHERE Sport = 'Cricket';
| MName | Fee |
|---|---|
| Arjun | 1500 |
| Aman | 1500 |
Explanation: WHERE keeps only the rows where Sport is 'Cricket': 2 of the 6 rows match (Arjun, Aman).
SELECT Sport, COUNT(*) FROM CLUB GROUP BY Sport;
| Sport | COUNT(*) |
|---|---|
| Chess | 2 |
| Cricket | 2 |
| Tennis | 2 |
Explanation: GROUP BY Sport makes 3 groups (Chess, Cricket, Tennis); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.
SELECT * FROM CLUB WHERE Fee BETWEEN 1000 AND 2200;
| MemNo | MName | Sport | Fee | Age |
|---|---|---|---|---|
| 1 | Arjun | Cricket | 1500 | 16 |
| 2 | Nisha | Tennis | 2200 | 15 |
| 3 | Aman | Cricket | 1500 | 17 |
| 5 | Ankit | Tennis | 2200 | 16 |
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).
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.
Write SQL queries for the following, based on the table CLUB.
Table: CLUB
| MemNo | MName | Sport | Fee | Age |
|---|---|---|---|---|
| 1 | Arjun | Cricket | 1500 | 16 |
| 2 | Nisha | Tennis | 2200 | 15 |
| 3 | Aman | Cricket | 1500 | 17 |
| 4 | Pooja | Chess | 800 | 14 |
| 5 | Ankit | Tennis | 2200 | 16 |
| 6 | Ritu | Chess | 800 | 15 |
SELECT * FROM CLUB ORDER BY Fee DESC;
| MemNo | MName | Sport | Fee | Age |
|---|---|---|---|---|
| 2 | Nisha | Tennis | 2200 | 15 |
| 5 | Ankit | Tennis | 2200 | 16 |
| 1 | Arjun | Cricket | 1500 | 16 |
| 3 | Aman | Cricket | 1500 | 17 |
| 4 | Pooja | Chess | 800 | 14 |
| 6 | Ritu | Chess | 800 | 15 |
Explanation: ORDER BY Fee arranges the result in descending (largest first) order.
SELECT MAX(Fee), MIN(Fee) FROM CLUB;
| MAX(Fee) | MIN(Fee) |
|---|---|
| 2200 | 800 |
Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.
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'.
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.
Write SQL queries for the following, based on the table CLUB.
Table: CLUB
| MemNo | MName | Sport | Fee | Age |
|---|---|---|---|---|
| 1 | Arjun | Cricket | 1500 | 16 |
| 2 | Nisha | Tennis | 2200 | 15 |
| 3 | Aman | Cricket | 1500 | 17 |
| 4 | Pooja | Chess | 800 | 14 |
| 5 | Ankit | Tennis | 2200 | 16 |
| 6 | Ritu | Chess | 800 | 15 |
SELECT DISTINCT Sport FROM CLUB;
| Sport |
|---|
| Cricket |
| Tennis |
| Chess |
Explanation: DISTINCT removes the repeated rows from the result of all the rows.
SELECT Sport, COUNT(*) FROM CLUB GROUP BY Sport HAVING COUNT(*) > 1;
| Sport | COUNT(*) |
|---|---|
| Chess | 2 |
| Cricket | 2 |
| Tennis | 2 |
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.
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).
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.
Write SQL queries for the following, based on the table GARMENT.
Table: GARMENT
| GCode | GName | Size | Price | Qty |
|---|---|---|---|---|
| G1 | Kurta | M | 650 | 20 |
| G2 | Jeans | L | 1200 | 15 |
| G3 | Shirt | M | 800 | 25 |
| G4 | Jacket | XL | 2400 | 6 |
| G5 | Saree | L | 1800 | 10 |
| G6 | Skirt | M | 700 | 12 |
SELECT GName, Price FROM GARMENT WHERE Size = 'M';
| GName | Price |
|---|---|
| Kurta | 650 |
| Shirt | 800 |
| Skirt | 700 |
Explanation: WHERE keeps only the rows where Size is 'M': 3 of the 6 rows match (G1, G3, G6).
SELECT Size, COUNT(*) FROM GARMENT GROUP BY Size;
| Size | COUNT(*) |
|---|---|
| L | 2 |
| M | 3 |
| XL | 1 |
Explanation: GROUP BY Size makes 3 groups (L, M, XL); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.
SELECT * FROM GARMENT WHERE Price BETWEEN 700 AND 1800;
| GCode | GName | Size | Price | Qty |
|---|---|---|---|---|
| G2 | Jeans | L | 1200 | 15 |
| G3 | Shirt | M | 800 | 25 |
| G5 | Saree | L | 1800 | 10 |
| G6 | Skirt | M | 700 | 12 |
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).
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.
Write SQL queries for the following, based on the table GARMENT.
Table: GARMENT
| GCode | GName | Size | Price | Qty |
|---|---|---|---|---|
| G1 | Kurta | M | 650 | 20 |
| G2 | Jeans | L | 1200 | 15 |
| G3 | Shirt | M | 800 | 25 |
| G4 | Jacket | XL | 2400 | 6 |
| G5 | Saree | L | 1800 | 10 |
| G6 | Skirt | M | 700 | 12 |
SELECT * FROM GARMENT ORDER BY Price DESC;
| GCode | GName | Size | Price | Qty |
|---|---|---|---|---|
| G4 | Jacket | XL | 2400 | 6 |
| G5 | Saree | L | 1800 | 10 |
| G2 | Jeans | L | 1200 | 15 |
| G3 | Shirt | M | 800 | 25 |
| G6 | Skirt | M | 700 | 12 |
| G1 | Kurta | M | 650 | 20 |
Explanation: ORDER BY Price arranges the result in descending (largest first) order.
SELECT MAX(Price), MIN(Price) FROM GARMENT;
| MAX(Price) | MIN(Price) |
|---|---|
| 2400 | 650 |
Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.
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'.
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.
Write SQL queries for the following, based on the table GARMENT.
Table: GARMENT
| GCode | GName | Size | Price | Qty |
|---|---|---|---|---|
| G1 | Kurta | M | 650 | 20 |
| G2 | Jeans | L | 1200 | 15 |
| G3 | Shirt | M | 800 | 25 |
| G4 | Jacket | XL | 2400 | 6 |
| G5 | Saree | L | 1800 | 10 |
| G6 | Skirt | M | 700 | 12 |
SELECT DISTINCT Size FROM GARMENT;
| Size |
|---|
| M |
| L |
| XL |
Explanation: DISTINCT removes the repeated rows from the result of all the rows.
SELECT Size, COUNT(*) FROM GARMENT GROUP BY Size HAVING COUNT(*) > 1;
| Size | COUNT(*) |
|---|---|
| L | 2 |
| M | 3 |
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.
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).
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.
Write SQL queries for the following, based on the table COURSE.
Table: COURSE
| CID | CName | Mode | Fees | Seats |
|---|---|---|---|---|
| C1 | Python Basics | Online | 3000 | 60 |
| C2 | Data Science | Offline | 12000 | 30 |
| C3 | Web Design | Online | 4500 | 50 |
| C4 | Cyber Safety | Online | 2500 | 80 |
| C5 | Robotics | Offline | 9000 | 25 |
| C6 | AI Basics | Offline | 7000 | 40 |
SELECT CName, Fees FROM COURSE WHERE Mode = 'Online';
| CName | Fees |
|---|---|
| Python Basics | 3000 |
| Web Design | 4500 |
| Cyber Safety | 2500 |
Explanation: WHERE keeps only the rows where Mode is 'Online': 3 of the 6 rows match (C1, C3, C4).
SELECT Mode, COUNT(*) FROM COURSE GROUP BY Mode;
| Mode | COUNT(*) |
|---|---|
| Offline | 3 |
| Online | 3 |
Explanation: GROUP BY Mode makes 2 groups (Offline, Online); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.
SELECT * FROM COURSE WHERE Fees BETWEEN 3000 AND 9000;
| CID | CName | Mode | Fees | Seats |
|---|---|---|---|---|
| C1 | Python Basics | Online | 3000 | 60 |
| C3 | Web Design | Online | 4500 | 50 |
| C5 | Robotics | Offline | 9000 | 25 |
| C6 | AI Basics | Offline | 7000 | 40 |
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).
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.
Write SQL queries for the following, based on the table COURSE.
Table: COURSE
| CID | CName | Mode | Fees | Seats |
|---|---|---|---|---|
| C1 | Python Basics | Online | 3000 | 60 |
| C2 | Data Science | Offline | 12000 | 30 |
| C3 | Web Design | Online | 4500 | 50 |
| C4 | Cyber Safety | Online | 2500 | 80 |
| C5 | Robotics | Offline | 9000 | 25 |
| C6 | AI Basics | Offline | 7000 | 40 |
SELECT * FROM COURSE ORDER BY Fees DESC;
| CID | CName | Mode | Fees | Seats |
|---|---|---|---|---|
| C2 | Data Science | Offline | 12000 | 30 |
| C5 | Robotics | Offline | 9000 | 25 |
| C6 | AI Basics | Offline | 7000 | 40 |
| C3 | Web Design | Online | 4500 | 50 |
| C1 | Python Basics | Online | 3000 | 60 |
| C4 | Cyber Safety | Online | 2500 | 80 |
Explanation: ORDER BY Fees arranges the result in descending (largest first) order.
SELECT MAX(Fees), MIN(Fees) FROM COURSE;
| MAX(Fees) | MIN(Fees) |
|---|---|
| 12000 | 2500 |
Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.
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'.
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.
Write SQL queries for the following, based on the table COURSE.
Table: COURSE
| CID | CName | Mode | Fees | Seats |
|---|---|---|---|---|
| C1 | Python Basics | Online | 3000 | 60 |
| C2 | Data Science | Offline | 12000 | 30 |
| C3 | Web Design | Online | 4500 | 50 |
| C4 | Cyber Safety | Online | 2500 | 80 |
| C5 | Robotics | Offline | 9000 | 25 |
| C6 | AI Basics | Offline | 7000 | 40 |
SELECT DISTINCT Mode FROM COURSE;
| Mode |
|---|
| Online |
| Offline |
Explanation: DISTINCT removes the repeated rows from the result of all the rows.
SELECT Mode, COUNT(*) FROM COURSE GROUP BY Mode HAVING COUNT(*) > 1;
| Mode | COUNT(*) |
|---|---|
| Offline | 3 |
| Online | 3 |
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.
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).
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.
Write SQL queries for the following, based on the table HOSTEL.
Table: HOSTEL
| RoomNo | SName | Block | Rent | Sem |
|---|---|---|---|---|
| 101 | Kiran | A | 4000 | 1 |
| 102 | Deepa | B | 4500 | 2 |
| 103 | Kavya | A | 4000 | 1 |
| 104 | Lata | C | 5200 | 3 |
| 105 | Komal | B | 4500 | 2 |
| 106 | Divya | C | 5200 | 1 |
SELECT SName, Rent FROM HOSTEL WHERE Block = 'A';
| SName | Rent |
|---|---|
| Kiran | 4000 |
| Kavya | 4000 |
Explanation: WHERE keeps only the rows where Block is 'A': 2 of the 6 rows match (Kiran, Kavya).
SELECT Block, COUNT(*) FROM HOSTEL GROUP BY Block;
| Block | COUNT(*) |
|---|---|
| A | 2 |
| B | 2 |
| C | 2 |
Explanation: GROUP BY Block makes 3 groups (A, B, C); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.
SELECT * FROM HOSTEL WHERE Rent BETWEEN 4200 AND 5200;
| RoomNo | SName | Block | Rent | Sem |
|---|---|---|---|---|
| 102 | Deepa | B | 4500 | 2 |
| 104 | Lata | C | 5200 | 3 |
| 105 | Komal | B | 4500 | 2 |
| 106 | Divya | C | 5200 | 1 |
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).
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.
Write SQL queries for the following, based on the table HOSTEL.
Table: HOSTEL
| RoomNo | SName | Block | Rent | Sem |
|---|---|---|---|---|
| 101 | Kiran | A | 4000 | 1 |
| 102 | Deepa | B | 4500 | 2 |
| 103 | Kavya | A | 4000 | 1 |
| 104 | Lata | C | 5200 | 3 |
| 105 | Komal | B | 4500 | 2 |
| 106 | Divya | C | 5200 | 1 |
SELECT * FROM HOSTEL ORDER BY Rent DESC;
| RoomNo | SName | Block | Rent | Sem |
|---|---|---|---|---|
| 104 | Lata | C | 5200 | 3 |
| 106 | Divya | C | 5200 | 1 |
| 102 | Deepa | B | 4500 | 2 |
| 105 | Komal | B | 4500 | 2 |
| 101 | Kiran | A | 4000 | 1 |
| 103 | Kavya | A | 4000 | 1 |
Explanation: ORDER BY Rent arranges the result in descending (largest first) order.
SELECT MAX(Rent), MIN(Rent) FROM HOSTEL;
| MAX(Rent) | MIN(Rent) |
|---|---|
| 5200 | 4000 |
Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.
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'.
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.
Write SQL queries for the following, based on the table HOSTEL.
Table: HOSTEL
| RoomNo | SName | Block | Rent | Sem |
|---|---|---|---|---|
| 101 | Kiran | A | 4000 | 1 |
| 102 | Deepa | B | 4500 | 2 |
| 103 | Kavya | A | 4000 | 1 |
| 104 | Lata | C | 5200 | 3 |
| 105 | Komal | B | 4500 | 2 |
| 106 | Divya | C | 5200 | 1 |
SELECT DISTINCT Block FROM HOSTEL;
| Block |
|---|
| A |
| B |
| C |
Explanation: DISTINCT removes the repeated rows from the result of all the rows.
SELECT Block, COUNT(*) FROM HOSTEL GROUP BY Block HAVING COUNT(*) > 1;
| Block | COUNT(*) |
|---|---|
| A | 2 |
| B | 2 |
| C | 2 |
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.
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).
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.
Write SQL queries for the following, based on the table BUS.
Table: BUS
| BusNo | Route | Depot | Seats | Fare |
|---|---|---|---|---|
| B1 | Airport Link | North | 40 | 60 |
| B2 | City Circle | South | 52 | 25 |
| B3 | Metro Feeder | North | 30 | 15 |
| B4 | Ring Road | East | 52 | 35 |
| B5 | Hill View | South | 36 | 45 |
| B6 | Lake Line | East | 40 | 30 |
SELECT Route, Fare FROM BUS WHERE Depot = 'North';
| Route | Fare |
|---|---|
| Airport Link | 60 |
| Metro Feeder | 15 |
Explanation: WHERE keeps only the rows where Depot is 'North': 2 of the 6 rows match (B1, B3).
SELECT Depot, COUNT(*) FROM BUS GROUP BY Depot;
| Depot | COUNT(*) |
|---|---|
| East | 2 |
| North | 2 |
| South | 2 |
Explanation: GROUP BY Depot makes 3 groups (East, North, South); the aggregate function is worked out separately for each group. COUNT(*) counts the rows.
SELECT * FROM BUS WHERE Fare BETWEEN 25 AND 45;
| BusNo | Route | Depot | Seats | Fare |
|---|---|---|---|---|
| B2 | City Circle | South | 52 | 25 |
| B4 | Ring Road | East | 52 | 35 |
| B5 | Hill View | South | 36 | 45 |
| B6 | Lake Line | East | 40 | 30 |
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).
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.
Write SQL queries for the following, based on the table BUS.
Table: BUS
| BusNo | Route | Depot | Seats | Fare |
|---|---|---|---|---|
| B1 | Airport Link | North | 40 | 60 |
| B2 | City Circle | South | 52 | 25 |
| B3 | Metro Feeder | North | 30 | 15 |
| B4 | Ring Road | East | 52 | 35 |
| B5 | Hill View | South | 36 | 45 |
| B6 | Lake Line | East | 40 | 30 |
SELECT * FROM BUS ORDER BY Fare DESC;
| BusNo | Route | Depot | Seats | Fare |
|---|---|---|---|---|
| B1 | Airport Link | North | 40 | 60 |
| B5 | Hill View | South | 36 | 45 |
| B4 | Ring Road | East | 52 | 35 |
| B6 | Lake Line | East | 40 | 30 |
| B2 | City Circle | South | 52 | 25 |
| B3 | Metro Feeder | North | 30 | 15 |
Explanation: ORDER BY Fare arranges the result in descending (largest first) order.
SELECT MAX(Fare), MIN(Fare) FROM BUS;
| MAX(Fare) | MIN(Fare) |
|---|---|
| 60 | 15 |
Explanation: MAX gives the largest value of all the rows. MIN gives the smallest value.
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'.
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.
Write SQL queries for the following, based on the table BUS.
Table: BUS
| BusNo | Route | Depot | Seats | Fare |
|---|---|---|---|---|
| B1 | Airport Link | North | 40 | 60 |
| B2 | City Circle | South | 52 | 25 |
| B3 | Metro Feeder | North | 30 | 15 |
| B4 | Ring Road | East | 52 | 35 |
| B5 | Hill View | South | 36 | 45 |
| B6 | Lake Line | East | 40 | 30 |
SELECT DISTINCT Depot FROM BUS;
| Depot |
|---|
| North |
| South |
| East |
Explanation: DISTINCT removes the repeated rows from the result of all the rows.
SELECT Depot, COUNT(*) FROM BUS GROUP BY Depot HAVING COUNT(*) > 1;
| Depot | COUNT(*) |
|---|---|
| East | 2 |
| North | 2 |
| South | 2 |
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.
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).
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.
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).
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 totalStates.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.
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()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.
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 cStudent.csv stores RNo, Name, Marks. Write Add() to input one record and append it, and Topper() to display the records with marks above 90.
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()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.
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()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.
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()Books.csv stores BNo, Title, Price. Write Search() to input a book number and display its record, or "Not found".
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()Score.csv stores Player, Runs. Write Highest() to display the name and runs of the highest scorer.
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()Result.csv stores RNo, Name, Marks. Write CopyFail() to copy the records with marks below 33 into Fail.csv.
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()Weather.csv stores City, Temperature. Write AvgTemp() to return the average temperature of all the cities.
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 / nLibrary.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.
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()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.
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 totalLibrary.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".
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()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.
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()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.
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 totalHostel.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".
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()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.
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()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.
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 totalCanteen.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".
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()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.
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()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.
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 totalSports.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".
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()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.
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()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.
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 totalTour.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".
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()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.
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()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.
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 totalStaff.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".
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()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.
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()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.
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 totalGarden.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".
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()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.
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()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.
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 totalPhone.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".
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()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.
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()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.
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 totalExam.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".
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()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.
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()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.
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 totalBus.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".
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()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:
Table: Chess_Event
| Event_ID | Event_Name | Event_Date | Venue | Max_Participants |
|---|---|---|---|---|
| Columns only. The rows are given in the question paper. | ||||
Table: Registrations
| Reg_ID | Student_Name | Class | Event_ID | Registration_Date |
|---|---|---|---|---|
| Columns only. The rows are given in the question paper. | ||||
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;Tables CUSTOMERS (C_ID, C_Name ...) and LOANS (C_ID, L_Amt, RoI, L_Date, Terms ...). Write queries to:
Table: CUSTOMERS
| C_ID | C_Name |
|---|---|
| Columns only. The rows are given in the question paper. | |
Table: LOANS
| C_ID | L_Amt | RoI | L_Date | Terms |
|---|---|---|---|---|
| Columns only. The rows are given in the question paper. | ||||
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;
Tables Artists (A_Code, Name ...) and Articles (A_Code, Article, DOC, Price ...). Write queries to:
Table: Artists
| A_Code | Name |
|---|---|
| Columns only. The rows are given in the question paper. | |
Table: Articles
| A_Code | Article | DOC | Price |
|---|---|---|---|
| Columns only. The rows are given in the question paper. | |||
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';
Tables STUDENT (RNo, Name, Class) and FEE (RNo, Amount, PayDate). Write queries to:
Table: STUDENT
| RNo | Name | Class |
|---|---|---|
| Columns only. The rows are given in the question paper. | ||
Table: FEE
| RNo | Amount | PayDate |
|---|---|---|
| Columns only. The rows are given in the question paper. | ||
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;
Tables EMPLOYEE (ENo, EName, DNo, Salary) and DEPARTMENT (DNo, DName, Location). Write queries to:
Table: EMPLOYEE
| ENo | EName | DNo | Salary |
|---|---|---|---|
| Columns only. The rows are given in the question paper. | |||
Table: DEPARTMENT
| DNo | DName | Location |
|---|---|---|
| Columns only. The rows are given in the question paper. | ||
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';
Tables PRODUCT (PID, PName, SID, Price) and SUPPLIER (SID, SName, City). Write queries to:
Table: PRODUCT
| PID | PName | SID | Price |
|---|---|---|---|
| Columns only. The rows are given in the question paper. | |||
Table: SUPPLIER
| SID | SName | City |
|---|---|---|
| Columns only. The rows are given in the question paper. | ||
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;
Tables DOCTOR (DID, DName, Dept) and PATIENT (PID, PName, DID, AdmitDate). Write queries to:
Table: DOCTOR
| DID | DName | Dept |
|---|---|---|
| Columns only. The rows are given in the question paper. | ||
Table: PATIENT
| PID | PName | DID | AdmitDate |
|---|---|---|---|
| Columns only. The rows are given in the question paper. | |||
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';
Tables BOOK (BNo, Title, Price) and ISSUE (BNo, MemberName, IssueDate). Write queries to:
Table: BOOK
| BNo | Title | Price |
|---|---|---|
| Columns only. The rows are given in the question paper. | ||
Table: ISSUE
| BNo | MemberName | IssueDate |
|---|---|---|
| Columns only. The rows are given in the question paper. | ||
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';
Tables TEAM (TID, TName, City) and PLAYER (PID, PName, TID, Runs). Write queries to:
Table: TEAM
| TID | TName | City |
|---|---|---|
| Columns only. The rows are given in the question paper. | ||
Table: PLAYER
| PID | PName | TID | Runs |
|---|---|---|---|
| Columns only. The rows are given in the question paper. | |||
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;
Tables CUSTOMER (CID, CName, City) and ORDERS (ONo, CID, Amount, ODate). Write queries to:
Table: CUSTOMER
| CID | CName | City |
|---|---|---|
| Columns only. The rows are given in the question paper. | ||
Table: ORDERS
| ONo | CID | Amount | ODate |
|---|---|---|---|
| Columns only. The rows are given in the question paper. | |||
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;
Write SQL queries for the following, based on the tables DEPT and STAFF.
Table: DEPT
| DNo | DName | Floor |
|---|---|---|
| 10 | Accounts | 1 |
| 20 | Sales | 2 |
| 30 | IT | 3 |
Table: STAFF
| SNo | SName | DNo | Pay |
|---|---|---|---|
| 1 | Asha | 10 | 42000 |
| 2 | Bilal | 20 | 38000 |
| 3 | Chitra | 30 | 65000 |
| 4 | Dev | 20 | 41000 |
| 5 | Esha | 30 | 58000 |
SELECT SName, DName FROM DEPT, STAFF WHERE DEPT.DNo = STAFF.DNo;
| SName | DName |
|---|---|
| Asha | Accounts |
| Bilal | Sales |
| Dev | Sales |
| Chitra | IT |
| Esha | IT |
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.
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'.
SELECT DName, SUM(Pay) FROM DEPT, STAFF WHERE DEPT.DNo = STAFF.DNo GROUP BY DName;
| DName | SUM(Pay) |
|---|---|
| Accounts | 42000 |
| IT | 123000 |
| Sales | 79000 |
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.
SELECT * FROM DEPT NATURAL JOIN STAFF;
| DNo | DName | Floor | SNo | SName | Pay |
|---|---|---|---|---|---|
| 10 | Accounts | 1 | 1 | Asha | 42000 |
| 20 | Sales | 2 | 2 | Bilal | 38000 |
| 20 | Sales | 2 | 4 | Dev | 41000 |
| 30 | IT | 3 | 3 | Chitra | 65000 |
| 30 | IT | 3 | 5 | Esha | 58000 |
Explanation: NATURAL JOIN joins DEPT and STAFF on their common column, which is shown only once.
Write SQL queries for the following, based on the tables DEPT and STAFF.
Table: DEPT
| DNo | DName | Floor |
|---|---|---|
| 10 | Accounts | 1 |
| 20 | Sales | 2 |
| 30 | IT | 3 |
Table: STAFF
| SNo | SName | DNo | Pay |
|---|---|---|---|
| 1 | Asha | 10 | 42000 |
| 2 | Bilal | 20 | 38000 |
| 3 | Chitra | 30 | 65000 |
| 4 | Dev | 20 | 41000 |
| 5 | Esha | 30 | 58000 |
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.
SELECT DName, SName, Pay FROM DEPT, STAFF WHERE DEPT.DNo = STAFF.DNo AND Pay > 40000;
| DName | SName | Pay |
|---|---|---|
| Accounts | Asha | 42000 |
| IT | Chitra | 65000 |
| Sales | Dev | 41000 |
| IT | Esha | 58000 |
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.
SELECT DName, COUNT(*) FROM DEPT, STAFF WHERE DEPT.DNo = STAFF.DNo GROUP BY DName;
| DName | COUNT(*) |
|---|---|
| Accounts | 1 |
| IT | 2 |
| Sales | 2 |
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.
SELECT * FROM STAFF ORDER BY Pay DESC;
| SNo | SName | DNo | Pay |
|---|---|---|---|
| 3 | Chitra | 30 | 65000 |
| 5 | Esha | 30 | 58000 |
| 1 | Asha | 10 | 42000 |
| 4 | Dev | 20 | 41000 |
| 2 | Bilal | 20 | 38000 |
Explanation: ORDER BY Pay arranges the result in descending (largest first) order.
Write SQL queries for the following, based on the tables DEPT and STAFF.
Table: DEPT
| DNo | DName | Floor |
|---|---|---|
| 10 | Accounts | 1 |
| 20 | Sales | 2 |
| 30 | IT | 3 |
Table: STAFF
| SNo | SName | DNo | Pay |
|---|---|---|---|
| 1 | Asha | 10 | 42000 |
| 2 | Bilal | 20 | 38000 |
| 3 | Chitra | 30 | 65000 |
| 4 | Dev | 20 | 41000 |
| 5 | Esha | 30 | 58000 |
SELECT SName, DName FROM DEPT, STAFF WHERE DEPT.DNo = STAFF.DNo AND Pay BETWEEN 40000 AND 60000;
| SName | DName |
|---|---|
| Asha | Accounts |
| Dev | Sales |
| Esha | IT |
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).
SELECT DName, MAX(Pay) FROM DEPT, STAFF WHERE DEPT.DNo = STAFF.DNo GROUP BY DName;
| DName | MAX(Pay) |
|---|---|
| Accounts | 42000 |
| IT | 65000 |
| Sales | 41000 |
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.
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.
SELECT DName, SName FROM DEPT, STAFF WHERE DEPT.DNo = STAFF.DNo ORDER BY SName;
| DName | SName |
|---|---|
| Accounts | Asha |
| Sales | Bilal |
| IT | Chitra |
| Sales | Dev |
| IT | Esha |
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.
Write SQL queries for the following, based on the tables CLASS and PUPIL.
Table: CLASS
| CNo | CName | Teacher |
|---|---|---|
| 11 | XI-A | Mr Rao |
| 12 | XI-B | Ms Sen |
| 13 | XII-A | Mr Khan |
Table: PUPIL
| RNo | PName | CNo | Marks |
|---|---|---|---|
| 1 | Aman | 11 | 78 |
| 2 | Bina | 12 | 91 |
| 3 | Chirag | 13 | 66 |
| 4 | Diya | 11 | 85 |
| 5 | Farid | 13 | 72 |
SELECT PName, CName FROM CLASS, PUPIL WHERE CLASS.CNo = PUPIL.CNo;
| PName | CName |
|---|---|
| Aman | XI-A |
| Diya | XI-A |
| Bina | XI-B |
| Chirag | XII-A |
| Farid | XII-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.
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'.
SELECT CName, SUM(Marks) FROM CLASS, PUPIL WHERE CLASS.CNo = PUPIL.CNo GROUP BY CName;
| CName | SUM(Marks) |
|---|---|
| XI-A | 163 |
| XI-B | 91 |
| XII-A | 138 |
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.
SELECT * FROM CLASS NATURAL JOIN PUPIL;
| CNo | CName | Teacher | RNo | PName | Marks |
|---|---|---|---|---|---|
| 11 | XI-A | Mr Rao | 1 | Aman | 78 |
| 11 | XI-A | Mr Rao | 4 | Diya | 85 |
| 12 | XI-B | Ms Sen | 2 | Bina | 91 |
| 13 | XII-A | Mr Khan | 3 | Chirag | 66 |
| 13 | XII-A | Mr Khan | 5 | Farid | 72 |
Explanation: NATURAL JOIN joins CLASS and PUPIL on their common column, which is shown only once.
Write SQL queries for the following, based on the tables CLASS and PUPIL.
Table: CLASS
| CNo | CName | Teacher |
|---|---|---|
| 11 | XI-A | Mr Rao |
| 12 | XI-B | Ms Sen |
| 13 | XII-A | Mr Khan |
Table: PUPIL
| RNo | PName | CNo | Marks |
|---|---|---|---|
| 1 | Aman | 11 | 78 |
| 2 | Bina | 12 | 91 |
| 3 | Chirag | 13 | 66 |
| 4 | Diya | 11 | 85 |
| 5 | Farid | 13 | 72 |
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.
SELECT CName, PName, Marks FROM CLASS, PUPIL WHERE CLASS.CNo = PUPIL.CNo AND Marks > 75;
| CName | PName | Marks |
|---|---|---|
| XI-A | Aman | 78 |
| XI-B | Bina | 91 |
| XI-A | Diya | 85 |
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.
SELECT CName, COUNT(*) FROM CLASS, PUPIL WHERE CLASS.CNo = PUPIL.CNo GROUP BY CName;
| CName | COUNT(*) |
|---|---|
| XI-A | 2 |
| XI-B | 1 |
| XII-A | 2 |
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.
SELECT * FROM PUPIL ORDER BY Marks DESC;
| RNo | PName | CNo | Marks |
|---|---|---|---|
| 2 | Bina | 12 | 91 |
| 4 | Diya | 11 | 85 |
| 1 | Aman | 11 | 78 |
| 5 | Farid | 13 | 72 |
| 3 | Chirag | 13 | 66 |
Explanation: ORDER BY Marks arranges the result in descending (largest first) order.
Write SQL queries for the following, based on the tables CLASS and PUPIL.
Table: CLASS
| CNo | CName | Teacher |
|---|---|---|
| 11 | XI-A | Mr Rao |
| 12 | XI-B | Ms Sen |
| 13 | XII-A | Mr Khan |
Table: PUPIL
| RNo | PName | CNo | Marks |
|---|---|---|---|
| 1 | Aman | 11 | 78 |
| 2 | Bina | 12 | 91 |
| 3 | Chirag | 13 | 66 |
| 4 | Diya | 11 | 85 |
| 5 | Farid | 13 | 72 |
SELECT PName, CName FROM CLASS, PUPIL WHERE CLASS.CNo = PUPIL.CNo AND Marks BETWEEN 70 AND 90;
| PName | CName |
|---|---|
| Aman | XI-A |
| Diya | XI-A |
| Farid | XII-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).
SELECT CName, MAX(Marks) FROM CLASS, PUPIL WHERE CLASS.CNo = PUPIL.CNo GROUP BY CName;
| CName | MAX(Marks) |
|---|---|
| XI-A | 85 |
| XI-B | 91 |
| XII-A | 72 |
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.
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.
SELECT CName, PName FROM CLASS, PUPIL WHERE CLASS.CNo = PUPIL.CNo ORDER BY PName;
| CName | PName |
|---|---|
| XI-A | Aman |
| XI-B | Bina |
| XII-A | Chirag |
| XI-A | Diya |
| XII-A | Farid |
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.
Write SQL queries for the following, based on the tables SHOP and SALE.
Table: SHOP
| SID | SName | Area |
|---|---|---|
| 1 | Fresh Mart | Rohini |
| 2 | City Store | Dwarka |
| 3 | Daily Needs | Saket |
Table: SALE
| BillNo | SID | Item | Amount |
|---|---|---|---|
| 501 | 1 | Rice | 1200 |
| 502 | 2 | Oil | 850 |
| 503 | 1 | Sugar | 400 |
| 504 | 3 | Tea | 300 |
| 505 | 2 | Atta | 950 |
SELECT Item, SName FROM SHOP, SALE WHERE SHOP.SID = SALE.SID;
| Item | SName |
|---|---|
| Rice | Fresh Mart |
| Sugar | Fresh Mart |
| Atta | City Store |
| Oil | City Store |
| Tea | Daily 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.
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'.
SELECT SName, SUM(Amount) FROM SHOP, SALE WHERE SHOP.SID = SALE.SID GROUP BY SName;
| SName | SUM(Amount) |
|---|---|
| City Store | 1800 |
| Daily Needs | 300 |
| Fresh Mart | 1600 |
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.
SELECT * FROM SHOP NATURAL JOIN SALE;
| SID | SName | Area | BillNo | Item | Amount |
|---|---|---|---|---|---|
| 1 | Fresh Mart | Rohini | 501 | Rice | 1200 |
| 1 | Fresh Mart | Rohini | 503 | Sugar | 400 |
| 2 | City Store | Dwarka | 502 | Oil | 850 |
| 2 | City Store | Dwarka | 505 | Atta | 950 |
| 3 | Daily Needs | Saket | 504 | Tea | 300 |
Explanation: NATURAL JOIN joins SHOP and SALE on their common column, which is shown only once.
Write SQL queries for the following, based on the tables SHOP and SALE.
Table: SHOP
| SID | SName | Area |
|---|---|---|
| 1 | Fresh Mart | Rohini |
| 2 | City Store | Dwarka |
| 3 | Daily Needs | Saket |
Table: SALE
| BillNo | SID | Item | Amount |
|---|---|---|---|
| 501 | 1 | Rice | 1200 |
| 502 | 2 | Oil | 850 |
| 503 | 1 | Sugar | 400 |
| 504 | 3 | Tea | 300 |
| 505 | 2 | Atta | 950 |
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.
SELECT SName, Item, Amount FROM SHOP, SALE WHERE SHOP.SID = SALE.SID AND Amount > 800;
| SName | Item | Amount |
|---|---|---|
| Fresh Mart | Rice | 1200 |
| City Store | Oil | 850 |
| City Store | Atta | 950 |
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.
SELECT SName, COUNT(*) FROM SHOP, SALE WHERE SHOP.SID = SALE.SID GROUP BY SName;
| SName | COUNT(*) |
|---|---|
| City Store | 2 |
| Daily Needs | 1 |
| Fresh Mart | 2 |
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.
SELECT * FROM SALE ORDER BY Amount DESC;
| BillNo | SID | Item | Amount |
|---|---|---|---|
| 501 | 1 | Rice | 1200 |
| 505 | 2 | Atta | 950 |
| 502 | 2 | Oil | 850 |
| 503 | 1 | Sugar | 400 |
| 504 | 3 | Tea | 300 |
Explanation: ORDER BY Amount arranges the result in descending (largest first) order.
Write SQL queries for the following, based on the tables SHOP and SALE.
Table: SHOP
| SID | SName | Area |
|---|---|---|
| 1 | Fresh Mart | Rohini |
| 2 | City Store | Dwarka |
| 3 | Daily Needs | Saket |
Table: SALE
| BillNo | SID | Item | Amount |
|---|---|---|---|
| 501 | 1 | Rice | 1200 |
| 502 | 2 | Oil | 850 |
| 503 | 1 | Sugar | 400 |
| 504 | 3 | Tea | 300 |
| 505 | 2 | Atta | 950 |
SELECT Item, SName FROM SHOP, SALE WHERE SHOP.SID = SALE.SID AND Amount BETWEEN 400 AND 1000;
| Item | SName |
|---|---|
| Oil | City Store |
| Sugar | Fresh Mart |
| Atta | City 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).
SELECT SName, MAX(Amount) FROM SHOP, SALE WHERE SHOP.SID = SALE.SID GROUP BY SName;
| SName | MAX(Amount) |
|---|---|
| City Store | 950 |
| Daily Needs | 300 |
| Fresh Mart | 1200 |
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.
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.
SELECT SName, Item FROM SHOP, SALE WHERE SHOP.SID = SALE.SID ORDER BY Item;
| SName | Item |
|---|---|
| City Store | Atta |
| City Store | Oil |
| Fresh Mart | Rice |
| Fresh Mart | Sugar |
| Daily Needs | Tea |
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.
Write SQL queries for the following, based on the tables AUTHOR and NOVEL.
Table: AUTHOR
| AID | AName | Country |
|---|---|---|
| 1 | R. Mehta | India |
| 2 | J. Carter | USA |
| 3 | S. Iyer | India |
Table: NOVEL
| NID | Title | AID | Price |
|---|---|---|---|
| 101 | Blue Sky | 1 | 350 |
| 102 | Lost Map | 2 | 499 |
| 103 | Green Hill | 1 | 275 |
| 104 | River Song | 3 | 420 |
| 105 | Night Train | 2 | 560 |
SELECT Title, AName FROM AUTHOR, NOVEL WHERE AUTHOR.AID = NOVEL.AID;
| Title | AName |
|---|---|
| Blue Sky | R. Mehta |
| Green Hill | R. Mehta |
| Lost Map | J. Carter |
| Night Train | J. Carter |
| River Song | S. 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.
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'.
SELECT AName, SUM(Price) FROM AUTHOR, NOVEL WHERE AUTHOR.AID = NOVEL.AID GROUP BY AName;
| AName | SUM(Price) |
|---|---|
| J. Carter | 1059 |
| R. Mehta | 625 |
| S. Iyer | 420 |
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.
SELECT * FROM AUTHOR NATURAL JOIN NOVEL;
| AID | AName | Country | NID | Title | Price |
|---|---|---|---|---|---|
| 1 | R. Mehta | India | 101 | Blue Sky | 350 |
| 1 | R. Mehta | India | 103 | Green Hill | 275 |
| 2 | J. Carter | USA | 102 | Lost Map | 499 |
| 2 | J. Carter | USA | 105 | Night Train | 560 |
| 3 | S. Iyer | India | 104 | River Song | 420 |
Explanation: NATURAL JOIN joins AUTHOR and NOVEL on their common column, which is shown only once.
Write SQL queries for the following, based on the tables AUTHOR and NOVEL.
Table: AUTHOR
| AID | AName | Country |
|---|---|---|
| 1 | R. Mehta | India |
| 2 | J. Carter | USA |
| 3 | S. Iyer | India |
Table: NOVEL
| NID | Title | AID | Price |
|---|---|---|---|
| 101 | Blue Sky | 1 | 350 |
| 102 | Lost Map | 2 | 499 |
| 103 | Green Hill | 1 | 275 |
| 104 | River Song | 3 | 420 |
| 105 | Night Train | 2 | 560 |
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.
SELECT AName, Title, Price FROM AUTHOR, NOVEL WHERE AUTHOR.AID = NOVEL.AID AND Price > 400;
| AName | Title | Price |
|---|---|---|
| J. Carter | Lost Map | 499 |
| S. Iyer | River Song | 420 |
| J. Carter | Night Train | 560 |
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.
SELECT AName, COUNT(*) FROM AUTHOR, NOVEL WHERE AUTHOR.AID = NOVEL.AID GROUP BY AName;
| AName | COUNT(*) |
|---|---|
| J. Carter | 2 |
| R. Mehta | 2 |
| S. Iyer | 1 |
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.
SELECT * FROM NOVEL ORDER BY Price DESC;
| NID | Title | AID | Price |
|---|---|---|---|
| 105 | Night Train | 2 | 560 |
| 102 | Lost Map | 2 | 499 |
| 104 | River Song | 3 | 420 |
| 101 | Blue Sky | 1 | 350 |
| 103 | Green Hill | 1 | 275 |
Explanation: ORDER BY Price arranges the result in descending (largest first) order.
Write SQL queries for the following, based on the tables AUTHOR and NOVEL.
Table: AUTHOR
| AID | AName | Country |
|---|---|---|
| 1 | R. Mehta | India |
| 2 | J. Carter | USA |
| 3 | S. Iyer | India |
Table: NOVEL
| NID | Title | AID | Price |
|---|---|---|---|
| 101 | Blue Sky | 1 | 350 |
| 102 | Lost Map | 2 | 499 |
| 103 | Green Hill | 1 | 275 |
| 104 | River Song | 3 | 420 |
| 105 | Night Train | 2 | 560 |
SELECT Title, AName FROM AUTHOR, NOVEL WHERE AUTHOR.AID = NOVEL.AID AND Price BETWEEN 300 AND 500;
| Title | AName |
|---|---|
| Blue Sky | R. Mehta |
| Lost Map | J. Carter |
| River Song | S. 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).
SELECT AName, MAX(Price) FROM AUTHOR, NOVEL WHERE AUTHOR.AID = NOVEL.AID GROUP BY AName;
| AName | MAX(Price) |
|---|---|
| J. Carter | 560 |
| R. Mehta | 350 |
| S. Iyer | 420 |
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.
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.
SELECT AName, Title FROM AUTHOR, NOVEL WHERE AUTHOR.AID = NOVEL.AID ORDER BY Title;
| AName | Title |
|---|---|
| R. Mehta | Blue Sky |
| R. Mehta | Green Hill |
| J. Carter | Lost Map |
| J. Carter | Night Train |
| S. Iyer | 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). The join gives 5 rows. ORDER BY Title arranges the result in ascending (smallest first) order.
Write SQL queries for the following, based on the tables ROUTE and TRIP.
Table: ROUTE
| RID | City | Distance |
|---|---|---|
| 1 | Jaipur | 280 |
| 2 | Agra | 230 |
| 3 | Shimla | 350 |
Table: TRIP
| TID | RID | Driver | Fare |
|---|---|---|---|
| 1 | 1 | Hari | 900 |
| 2 | 2 | Iqbal | 750 |
| 3 | 1 | Joseph | 950 |
| 4 | 3 | Kamal | 1400 |
| 5 | 2 | Hari | 800 |
SELECT Driver, City FROM ROUTE, TRIP WHERE ROUTE.RID = TRIP.RID;
| Driver | City |
|---|---|
| Hari | Jaipur |
| Joseph | Jaipur |
| Hari | Agra |
| Iqbal | Agra |
| Kamal | Shimla |
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.
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'.
SELECT City, SUM(Fare) FROM ROUTE, TRIP WHERE ROUTE.RID = TRIP.RID GROUP BY City;
| City | SUM(Fare) |
|---|---|
| Agra | 1550 |
| Jaipur | 1850 |
| Shimla | 1400 |
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.
SELECT * FROM ROUTE NATURAL JOIN TRIP;
| RID | City | Distance | TID | Driver | Fare |
|---|---|---|---|---|---|
| 1 | Jaipur | 280 | 1 | Hari | 900 |
| 1 | Jaipur | 280 | 3 | Joseph | 950 |
| 2 | Agra | 230 | 2 | Iqbal | 750 |
| 2 | Agra | 230 | 5 | Hari | 800 |
| 3 | Shimla | 350 | 4 | Kamal | 1400 |
Explanation: NATURAL JOIN joins ROUTE and TRIP on their common column, which is shown only once.
Write SQL queries for the following, based on the tables ROUTE and TRIP.
Table: ROUTE
| RID | City | Distance |
|---|---|---|
| 1 | Jaipur | 280 |
| 2 | Agra | 230 |
| 3 | Shimla | 350 |
Table: TRIP
| TID | RID | Driver | Fare |
|---|---|---|---|
| 1 | 1 | Hari | 900 |
| 2 | 2 | Iqbal | 750 |
| 3 | 1 | Joseph | 950 |
| 4 | 3 | Kamal | 1400 |
| 5 | 2 | Hari | 800 |
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.
SELECT City, Driver, Fare FROM ROUTE, TRIP WHERE ROUTE.RID = TRIP.RID AND Fare > 850;
| City | Driver | Fare |
|---|---|---|
| Jaipur | Hari | 900 |
| Jaipur | Joseph | 950 |
| Shimla | Kamal | 1400 |
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.
SELECT City, COUNT(*) FROM ROUTE, TRIP WHERE ROUTE.RID = TRIP.RID GROUP BY City;
| City | COUNT(*) |
|---|---|
| Agra | 2 |
| Jaipur | 2 |
| Shimla | 1 |
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.
SELECT * FROM TRIP ORDER BY Fare DESC;
| TID | RID | Driver | Fare |
|---|---|---|---|
| 4 | 3 | Kamal | 1400 |
| 3 | 1 | Joseph | 950 |
| 1 | 1 | Hari | 900 |
| 5 | 2 | Hari | 800 |
| 2 | 2 | Iqbal | 750 |
Explanation: ORDER BY Fare arranges the result in descending (largest first) order.
Write SQL queries for the following, based on the tables ROUTE and TRIP.
Table: ROUTE
| RID | City | Distance |
|---|---|---|
| 1 | Jaipur | 280 |
| 2 | Agra | 230 |
| 3 | Shimla | 350 |
Table: TRIP
| TID | RID | Driver | Fare |
|---|---|---|---|
| 1 | 1 | Hari | 900 |
| 2 | 2 | Iqbal | 750 |
| 3 | 1 | Joseph | 950 |
| 4 | 3 | Kamal | 1400 |
| 5 | 2 | Hari | 800 |
SELECT Driver, City FROM ROUTE, TRIP WHERE ROUTE.RID = TRIP.RID AND Fare BETWEEN 800 AND 1000;
| Driver | City |
|---|---|
| Hari | Jaipur |
| Joseph | Jaipur |
| Hari | Agra |
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).
SELECT City, MAX(Fare) FROM ROUTE, TRIP WHERE ROUTE.RID = TRIP.RID GROUP BY City;
| City | MAX(Fare) |
|---|---|
| Agra | 800 |
| Jaipur | 950 |
| Shimla | 1400 |
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.
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.
SELECT City, Driver FROM ROUTE, TRIP WHERE ROUTE.RID = TRIP.RID ORDER BY Driver;
| City | Driver |
|---|---|
| Jaipur | Hari |
| Agra | Hari |
| Agra | Iqbal |
| Jaipur | Joseph |
| Shimla | Kamal |
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.
Write SQL queries for the following, based on the tables HOUSE and MEMBER.
Table: HOUSE
| HID | HName | Colour |
|---|---|---|
| 1 | Shivaji | Red |
| 2 | Tagore | Blue |
| 3 | Raman | Green |
Table: MEMBER
| MID | MName | HID | Points |
|---|---|---|---|
| 1 | Neha | 1 | 45 |
| 2 | Om | 2 | 60 |
| 3 | Pari | 3 | 38 |
| 4 | Qasim | 1 | 72 |
| 5 | Rhea | 2 | 55 |
SELECT MName, HName FROM HOUSE, MEMBER WHERE HOUSE.HID = MEMBER.HID;
| MName | HName |
|---|---|
| Neha | Shivaji |
| Qasim | Shivaji |
| Om | Tagore |
| Rhea | Tagore |
| Pari | Raman |
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.
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'.
SELECT HName, SUM(Points) FROM HOUSE, MEMBER WHERE HOUSE.HID = MEMBER.HID GROUP BY HName;
| HName | SUM(Points) |
|---|---|
| Raman | 38 |
| Shivaji | 117 |
| Tagore | 115 |
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.
SELECT * FROM HOUSE NATURAL JOIN MEMBER;
| HID | HName | Colour | MID | MName | Points |
|---|---|---|---|---|---|
| 1 | Shivaji | Red | 1 | Neha | 45 |
| 1 | Shivaji | Red | 4 | Qasim | 72 |
| 2 | Tagore | Blue | 2 | Om | 60 |
| 2 | Tagore | Blue | 5 | Rhea | 55 |
| 3 | Raman | Green | 3 | Pari | 38 |
Explanation: NATURAL JOIN joins HOUSE and MEMBER on their common column, which is shown only once.
Write SQL queries for the following, based on the tables HOUSE and MEMBER.
Table: HOUSE
| HID | HName | Colour |
|---|---|---|
| 1 | Shivaji | Red |
| 2 | Tagore | Blue |
| 3 | Raman | Green |
Table: MEMBER
| MID | MName | HID | Points |
|---|---|---|---|
| 1 | Neha | 1 | 45 |
| 2 | Om | 2 | 60 |
| 3 | Pari | 3 | 38 |
| 4 | Qasim | 1 | 72 |
| 5 | Rhea | 2 | 55 |
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.
SELECT HName, MName, Points FROM HOUSE, MEMBER WHERE HOUSE.HID = MEMBER.HID AND Points > 50;
| HName | MName | Points |
|---|---|---|
| Tagore | Om | 60 |
| Shivaji | Qasim | 72 |
| Tagore | Rhea | 55 |
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.
SELECT HName, COUNT(*) FROM HOUSE, MEMBER WHERE HOUSE.HID = MEMBER.HID GROUP BY HName;
| HName | COUNT(*) |
|---|---|
| Raman | 1 |
| Shivaji | 2 |
| Tagore | 2 |
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.
SELECT * FROM MEMBER ORDER BY Points DESC;
| MID | MName | HID | Points |
|---|---|---|---|
| 4 | Qasim | 1 | 72 |
| 2 | Om | 2 | 60 |
| 5 | Rhea | 2 | 55 |
| 1 | Neha | 1 | 45 |
| 3 | Pari | 3 | 38 |
Explanation: ORDER BY Points arranges the result in descending (largest first) order.
Write SQL queries for the following, based on the tables HOUSE and MEMBER.
Table: HOUSE
| HID | HName | Colour |
|---|---|---|
| 1 | Shivaji | Red |
| 2 | Tagore | Blue |
| 3 | Raman | Green |
Table: MEMBER
| MID | MName | HID | Points |
|---|---|---|---|
| 1 | Neha | 1 | 45 |
| 2 | Om | 2 | 60 |
| 3 | Pari | 3 | 38 |
| 4 | Qasim | 1 | 72 |
| 5 | Rhea | 2 | 55 |
SELECT MName, HName FROM HOUSE, MEMBER WHERE HOUSE.HID = MEMBER.HID AND Points BETWEEN 40 AND 60;
| MName | HName |
|---|---|
| Neha | Shivaji |
| Om | Tagore |
| Rhea | Tagore |
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).
SELECT HName, MAX(Points) FROM HOUSE, MEMBER WHERE HOUSE.HID = MEMBER.HID GROUP BY HName;
| HName | MAX(Points) |
|---|---|
| Raman | 38 |
| Shivaji | 72 |
| Tagore | 60 |
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.
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.
SELECT HName, MName FROM HOUSE, MEMBER WHERE HOUSE.HID = MEMBER.HID ORDER BY MName;
| HName | MName |
|---|---|
| Shivaji | Neha |
| Tagore | Om |
| Raman | Pari |
| Shivaji | Qasim |
| Tagore | Rhea |
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.
Write SQL queries for the following, based on the tables LAB and COMPUTER.
Table: LAB
| LID | LName | Incharge |
|---|---|---|
| 1 | Junior Lab | Ms Roy |
| 2 | Senior Lab | Mr Das |
| 3 | AI Lab | Ms Paul |
Table: COMPUTER
| CompNo | LID | Brand | RAM |
|---|---|---|---|
| 1 | 1 | Zenbook | 8 |
| 2 | 2 | Orbit | 16 |
| 3 | 2 | Zenbook | 8 |
| 4 | 3 | Lumo | 32 |
| 5 | 3 | Orbit | 16 |
SELECT Brand, LName FROM LAB, COMPUTER WHERE LAB.LID = COMPUTER.LID;
| Brand | LName |
|---|---|
| Zenbook | Junior Lab |
| Orbit | Senior Lab |
| Zenbook | Senior Lab |
| Lumo | AI Lab |
| Orbit | AI 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.
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'.
SELECT LName, SUM(RAM) FROM LAB, COMPUTER WHERE LAB.LID = COMPUTER.LID GROUP BY LName;
| LName | SUM(RAM) |
|---|---|
| AI Lab | 48 |
| Junior Lab | 8 |
| Senior Lab | 24 |
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.
SELECT * FROM LAB NATURAL JOIN COMPUTER;
| LID | LName | Incharge | CompNo | Brand | RAM |
|---|---|---|---|---|---|
| 1 | Junior Lab | Ms Roy | 1 | Zenbook | 8 |
| 2 | Senior Lab | Mr Das | 2 | Orbit | 16 |
| 2 | Senior Lab | Mr Das | 3 | Zenbook | 8 |
| 3 | AI Lab | Ms Paul | 4 | Lumo | 32 |
| 3 | AI Lab | Ms Paul | 5 | Orbit | 16 |
Explanation: NATURAL JOIN joins LAB and COMPUTER on their common column, which is shown only once.
Write SQL queries for the following, based on the tables LAB and COMPUTER.
Table: LAB
| LID | LName | Incharge |
|---|---|---|
| 1 | Junior Lab | Ms Roy |
| 2 | Senior Lab | Mr Das |
| 3 | AI Lab | Ms Paul |
Table: COMPUTER
| CompNo | LID | Brand | RAM |
|---|---|---|---|
| 1 | 1 | Zenbook | 8 |
| 2 | 2 | Orbit | 16 |
| 3 | 2 | Zenbook | 8 |
| 4 | 3 | Lumo | 32 |
| 5 | 3 | Orbit | 16 |
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.
SELECT LName, Brand, RAM FROM LAB, COMPUTER WHERE LAB.LID = COMPUTER.LID AND RAM > 8;
| LName | Brand | RAM |
|---|---|---|
| Senior Lab | Orbit | 16 |
| AI Lab | Lumo | 32 |
| AI Lab | Orbit | 16 |
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.
SELECT LName, COUNT(*) FROM LAB, COMPUTER WHERE LAB.LID = COMPUTER.LID GROUP BY LName;
| LName | COUNT(*) |
|---|---|
| AI Lab | 2 |
| Junior Lab | 1 |
| Senior Lab | 2 |
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.
SELECT * FROM COMPUTER ORDER BY RAM DESC;
| CompNo | LID | Brand | RAM |
|---|---|---|---|
| 4 | 3 | Lumo | 32 |
| 2 | 2 | Orbit | 16 |
| 5 | 3 | Orbit | 16 |
| 1 | 1 | Zenbook | 8 |
| 3 | 2 | Zenbook | 8 |
Explanation: ORDER BY RAM arranges the result in descending (largest first) order.
Write SQL queries for the following, based on the tables LAB and COMPUTER.
Table: LAB
| LID | LName | Incharge |
|---|---|---|
| 1 | Junior Lab | Ms Roy |
| 2 | Senior Lab | Mr Das |
| 3 | AI Lab | Ms Paul |
Table: COMPUTER
| CompNo | LID | Brand | RAM |
|---|---|---|---|
| 1 | 1 | Zenbook | 8 |
| 2 | 2 | Orbit | 16 |
| 3 | 2 | Zenbook | 8 |
| 4 | 3 | Lumo | 32 |
| 5 | 3 | Orbit | 16 |
SELECT Brand, LName FROM LAB, COMPUTER WHERE LAB.LID = COMPUTER.LID AND RAM BETWEEN 8 AND 16;
| Brand | LName |
|---|---|
| Zenbook | Junior Lab |
| Orbit | Senior Lab |
| Zenbook | Senior Lab |
| Orbit | AI 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).
SELECT LName, MAX(RAM) FROM LAB, COMPUTER WHERE LAB.LID = COMPUTER.LID GROUP BY LName;
| LName | MAX(RAM) |
|---|---|
| AI Lab | 32 |
| Junior Lab | 8 |
| Senior Lab | 16 |
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.
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.
SELECT LName, Brand FROM LAB, COMPUTER WHERE LAB.LID = COMPUTER.LID ORDER BY Brand;
| LName | Brand |
|---|---|
| AI Lab | Lumo |
| Senior Lab | Orbit |
| AI Lab | Orbit |
| Junior Lab | Zenbook |
| Senior Lab | Zenbook |
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.
Write SQL queries for the following, based on the tables CINEMA and SCREENING.
Table: CINEMA
| CID | CName | City |
|---|---|---|
| 1 | Galaxy | Indore |
| 2 | Regal | Bhopal |
| 3 | Orion | Indore |
Table: SCREENING
| ShowNo | CID | Film | Price |
|---|---|---|---|
| 1 | 1 | Udaan | 180 |
| 2 | 2 | Safar | 150 |
| 3 | 3 | Udaan | 220 |
| 4 | 1 | Nadi | 200 |
| 5 | 2 | Sapna | 160 |
SELECT Film, CName FROM CINEMA, SCREENING WHERE CINEMA.CID = SCREENING.CID;
| Film | CName |
|---|---|
| Nadi | Galaxy |
| Udaan | Galaxy |
| Safar | Regal |
| Sapna | Regal |
| Udaan | Orion |
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.
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'.
SELECT CName, SUM(Price) FROM CINEMA, SCREENING WHERE CINEMA.CID = SCREENING.CID GROUP BY CName;
| CName | SUM(Price) |
|---|---|
| Galaxy | 380 |
| Orion | 220 |
| Regal | 310 |
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.
SELECT * FROM CINEMA NATURAL JOIN SCREENING;
| CID | CName | City | ShowNo | Film | Price |
|---|---|---|---|---|---|
| 1 | Galaxy | Indore | 1 | Udaan | 180 |
| 1 | Galaxy | Indore | 4 | Nadi | 200 |
| 2 | Regal | Bhopal | 2 | Safar | 150 |
| 2 | Regal | Bhopal | 5 | Sapna | 160 |
| 3 | Orion | Indore | 3 | Udaan | 220 |
Explanation: NATURAL JOIN joins CINEMA and SCREENING on their common column, which is shown only once.
Write SQL queries for the following, based on the tables CINEMA and SCREENING.
Table: CINEMA
| CID | CName | City |
|---|---|---|
| 1 | Galaxy | Indore |
| 2 | Regal | Bhopal |
| 3 | Orion | Indore |
Table: SCREENING
| ShowNo | CID | Film | Price |
|---|---|---|---|
| 1 | 1 | Udaan | 180 |
| 2 | 2 | Safar | 150 |
| 3 | 3 | Udaan | 220 |
| 4 | 1 | Nadi | 200 |
| 5 | 2 | Sapna | 160 |
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.
SELECT CName, Film, Price FROM CINEMA, SCREENING WHERE CINEMA.CID = SCREENING.CID AND Price > 170;
| CName | Film | Price |
|---|---|---|
| Galaxy | Udaan | 180 |
| Orion | Udaan | 220 |
| Galaxy | Nadi | 200 |
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.
SELECT CName, COUNT(*) FROM CINEMA, SCREENING WHERE CINEMA.CID = SCREENING.CID GROUP BY CName;
| CName | COUNT(*) |
|---|---|
| Galaxy | 2 |
| Orion | 1 |
| Regal | 2 |
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.
SELECT * FROM SCREENING ORDER BY Price DESC;
| ShowNo | CID | Film | Price |
|---|---|---|---|
| 3 | 3 | Udaan | 220 |
| 4 | 1 | Nadi | 200 |
| 1 | 1 | Udaan | 180 |
| 5 | 2 | Sapna | 160 |
| 2 | 2 | Safar | 150 |
Explanation: ORDER BY Price arranges the result in descending (largest first) order.
Write SQL queries for the following, based on the tables CINEMA and SCREENING.
Table: CINEMA
| CID | CName | City |
|---|---|---|
| 1 | Galaxy | Indore |
| 2 | Regal | Bhopal |
| 3 | Orion | Indore |
Table: SCREENING
| ShowNo | CID | Film | Price |
|---|---|---|---|
| 1 | 1 | Udaan | 180 |
| 2 | 2 | Safar | 150 |
| 3 | 3 | Udaan | 220 |
| 4 | 1 | Nadi | 200 |
| 5 | 2 | Sapna | 160 |
SELECT Film, CName FROM CINEMA, SCREENING WHERE CINEMA.CID = SCREENING.CID AND Price BETWEEN 150 AND 200;
| Film | CName |
|---|---|
| Udaan | Galaxy |
| Safar | Regal |
| Nadi | Galaxy |
| Sapna | Regal |
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).
SELECT CName, MAX(Price) FROM CINEMA, SCREENING WHERE CINEMA.CID = SCREENING.CID GROUP BY CName;
| CName | MAX(Price) |
|---|---|
| Galaxy | 200 |
| Orion | 220 |
| Regal | 160 |
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.
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.
SELECT CName, Film FROM CINEMA, SCREENING WHERE CINEMA.CID = SCREENING.CID ORDER BY Film;
| CName | Film |
|---|---|
| Galaxy | Nadi |
| Regal | Safar |
| Regal | Sapna |
| Galaxy | Udaan |
| Orion | Udaan |
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.
Write SQL queries for the following, based on the tables FARM and CROP.
Table: FARM
| FID | Owner | Village |
|---|---|---|
| 1 | Balbir | Rampur |
| 2 | Savitri | Sonpur |
| 3 | Gurmeet | Rampur |
Table: CROP
| CropNo | FID | CropName | Yield |
|---|---|---|---|
| 1 | 1 | Wheat | 42 |
| 2 | 2 | Rice | 35 |
| 3 | 1 | Mustard | 18 |
| 4 | 3 | Wheat | 50 |
| 5 | 2 | Maize | 27 |
SELECT CropName, Owner FROM FARM, CROP WHERE FARM.FID = CROP.FID;
| CropName | Owner |
|---|---|
| Mustard | Balbir |
| Wheat | Balbir |
| Maize | Savitri |
| Rice | Savitri |
| Wheat | Gurmeet |
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.
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'.
SELECT Owner, SUM(Yield) FROM FARM, CROP WHERE FARM.FID = CROP.FID GROUP BY Owner;
| Owner | SUM(Yield) |
|---|---|
| Balbir | 60 |
| Gurmeet | 50 |
| Savitri | 62 |
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.
SELECT * FROM FARM NATURAL JOIN CROP;
| FID | Owner | Village | CropNo | CropName | Yield |
|---|---|---|---|---|---|
| 1 | Balbir | Rampur | 1 | Wheat | 42 |
| 1 | Balbir | Rampur | 3 | Mustard | 18 |
| 2 | Savitri | Sonpur | 2 | Rice | 35 |
| 2 | Savitri | Sonpur | 5 | Maize | 27 |
| 3 | Gurmeet | Rampur | 4 | Wheat | 50 |
Explanation: NATURAL JOIN joins FARM and CROP on their common column, which is shown only once.
Write SQL queries for the following, based on the tables FARM and CROP.
Table: FARM
| FID | Owner | Village |
|---|---|---|
| 1 | Balbir | Rampur |
| 2 | Savitri | Sonpur |
| 3 | Gurmeet | Rampur |
Table: CROP
| CropNo | FID | CropName | Yield |
|---|---|---|---|
| 1 | 1 | Wheat | 42 |
| 2 | 2 | Rice | 35 |
| 3 | 1 | Mustard | 18 |
| 4 | 3 | Wheat | 50 |
| 5 | 2 | Maize | 27 |
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.
SELECT Owner, CropName, Yield FROM FARM, CROP WHERE FARM.FID = CROP.FID AND Yield > 30;
| Owner | CropName | Yield |
|---|---|---|
| Balbir | Wheat | 42 |
| Savitri | Rice | 35 |
| Gurmeet | Wheat | 50 |
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.
SELECT Owner, COUNT(*) FROM FARM, CROP WHERE FARM.FID = CROP.FID GROUP BY Owner;
| Owner | COUNT(*) |
|---|---|
| Balbir | 2 |
| Gurmeet | 1 |
| Savitri | 2 |
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.
SELECT * FROM CROP ORDER BY Yield DESC;
| CropNo | FID | CropName | Yield |
|---|---|---|---|
| 4 | 3 | Wheat | 50 |
| 1 | 1 | Wheat | 42 |
| 2 | 2 | Rice | 35 |
| 5 | 2 | Maize | 27 |
| 3 | 1 | Mustard | 18 |
Explanation: ORDER BY Yield arranges the result in descending (largest first) order.
Write SQL queries for the following, based on the tables FARM and CROP.
Table: FARM
| FID | Owner | Village |
|---|---|---|
| 1 | Balbir | Rampur |
| 2 | Savitri | Sonpur |
| 3 | Gurmeet | Rampur |
Table: CROP
| CropNo | FID | CropName | Yield |
|---|---|---|---|
| 1 | 1 | Wheat | 42 |
| 2 | 2 | Rice | 35 |
| 3 | 1 | Mustard | 18 |
| 4 | 3 | Wheat | 50 |
| 5 | 2 | Maize | 27 |
SELECT CropName, Owner FROM FARM, CROP WHERE FARM.FID = CROP.FID AND Yield BETWEEN 25 AND 45;
| CropName | Owner |
|---|---|
| Wheat | Balbir |
| Rice | Savitri |
| Maize | Savitri |
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).
SELECT Owner, MAX(Yield) FROM FARM, CROP WHERE FARM.FID = CROP.FID GROUP BY Owner;
| Owner | MAX(Yield) |
|---|---|
| Balbir | 42 |
| Gurmeet | 50 |
| Savitri | 35 |
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.
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.
SELECT Owner, CropName FROM FARM, CROP WHERE FARM.FID = CROP.FID ORDER BY CropName;
| Owner | CropName |
|---|---|
| Savitri | Maize |
| Balbir | Mustard |
| Savitri | Rice |
| Balbir | Wheat |
| Gurmeet | Wheat |
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.
Write SQL queries for the following, based on the tables COACH and TRAINEE.
Table: COACH
| CID | CName | Game |
|---|---|---|
| 1 | Mr Gill | Hockey |
| 2 | Ms Nair | Badminton |
| 3 | Mr Bose | Football |
Table: TRAINEE
| TID | TName | CID | Score |
|---|---|---|---|
| 1 | Uday | 1 | 64 |
| 2 | Veena | 2 | 88 |
| 3 | Wasim | 3 | 71 |
| 4 | Yash | 1 | 79 |
| 5 | Zoya | 2 | 93 |
SELECT TName, CName FROM COACH, TRAINEE WHERE COACH.CID = TRAINEE.CID;
| TName | CName |
|---|---|
| Uday | Mr Gill |
| Yash | Mr Gill |
| Veena | Ms Nair |
| Zoya | Ms Nair |
| Wasim | Mr 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.
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'.
SELECT CName, SUM(Score) FROM COACH, TRAINEE WHERE COACH.CID = TRAINEE.CID GROUP BY CName;
| CName | SUM(Score) |
|---|---|
| Mr Bose | 71 |
| Mr Gill | 143 |
| Ms Nair | 181 |
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.
SELECT * FROM COACH NATURAL JOIN TRAINEE;
| CID | CName | Game | TID | TName | Score |
|---|---|---|---|---|---|
| 1 | Mr Gill | Hockey | 1 | Uday | 64 |
| 1 | Mr Gill | Hockey | 4 | Yash | 79 |
| 2 | Ms Nair | Badminton | 2 | Veena | 88 |
| 2 | Ms Nair | Badminton | 5 | Zoya | 93 |
| 3 | Mr Bose | Football | 3 | Wasim | 71 |
Explanation: NATURAL JOIN joins COACH and TRAINEE on their common column, which is shown only once.
Write SQL queries for the following, based on the tables COACH and TRAINEE.
Table: COACH
| CID | CName | Game |
|---|---|---|
| 1 | Mr Gill | Hockey |
| 2 | Ms Nair | Badminton |
| 3 | Mr Bose | Football |
Table: TRAINEE
| TID | TName | CID | Score |
|---|---|---|---|
| 1 | Uday | 1 | 64 |
| 2 | Veena | 2 | 88 |
| 3 | Wasim | 3 | 71 |
| 4 | Yash | 1 | 79 |
| 5 | Zoya | 2 | 93 |
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.
SELECT CName, TName, Score FROM COACH, TRAINEE WHERE COACH.CID = TRAINEE.CID AND Score > 75;
| CName | TName | Score |
|---|---|---|
| Ms Nair | Veena | 88 |
| Mr Gill | Yash | 79 |
| Ms Nair | Zoya | 93 |
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.
SELECT CName, COUNT(*) FROM COACH, TRAINEE WHERE COACH.CID = TRAINEE.CID GROUP BY CName;
| CName | COUNT(*) |
|---|---|
| Mr Bose | 1 |
| Mr Gill | 2 |
| Ms Nair | 2 |
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.
SELECT * FROM TRAINEE ORDER BY Score DESC;
| TID | TName | CID | Score |
|---|---|---|---|
| 5 | Zoya | 2 | 93 |
| 2 | Veena | 2 | 88 |
| 4 | Yash | 1 | 79 |
| 3 | Wasim | 3 | 71 |
| 1 | Uday | 1 | 64 |
Explanation: ORDER BY Score arranges the result in descending (largest first) order.
Write SQL queries for the following, based on the tables COACH and TRAINEE.
Table: COACH
| CID | CName | Game |
|---|---|---|
| 1 | Mr Gill | Hockey |
| 2 | Ms Nair | Badminton |
| 3 | Mr Bose | Football |
Table: TRAINEE
| TID | TName | CID | Score |
|---|---|---|---|
| 1 | Uday | 1 | 64 |
| 2 | Veena | 2 | 88 |
| 3 | Wasim | 3 | 71 |
| 4 | Yash | 1 | 79 |
| 5 | Zoya | 2 | 93 |
SELECT TName, CName FROM COACH, TRAINEE WHERE COACH.CID = TRAINEE.CID AND Score BETWEEN 70 AND 90;
| TName | CName |
|---|---|
| Veena | Ms Nair |
| Wasim | Mr Bose |
| Yash | Mr 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).
SELECT CName, MAX(Score) FROM COACH, TRAINEE WHERE COACH.CID = TRAINEE.CID GROUP BY CName;
| CName | MAX(Score) |
|---|---|
| Mr Bose | 71 |
| Mr Gill | 79 |
| Ms Nair | 93 |
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.
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.
SELECT CName, TName FROM COACH, TRAINEE WHERE COACH.CID = TRAINEE.CID ORDER BY TName;
| CName | TName |
|---|---|
| Mr Gill | Uday |
| Ms Nair | Veena |
| Mr Bose | Wasim |
| Mr Gill | Yash |
| Ms Nair | Zoya |
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.
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.
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()Write a program to display all the records of the table Account in the database SCHOOL where Fees is less than 5000.
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()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.
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()Table STUDENT (RNo, Name, Marks) is in the database SCHOOL. Write a function AddStudent() that inputs one record and inserts it into the table.
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()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.
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()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.
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()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".
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()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.
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()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.
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()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).
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()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.)
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()A college keeps enrolment records with Roll_No, Student_Name, Course and Fees in a binary file. Write:
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()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.
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()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%.
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()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.
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 cEMP.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.
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()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.
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()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.
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 cPLAYER.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.
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()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.
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)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.
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()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.
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 cTOY.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".
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()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.
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)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.
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 cGYM.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".
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()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.
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)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.
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 cLAPTOP.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".
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()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.
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)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.
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 cCROP.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".
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()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.
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)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.
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 cFILM.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".
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()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.
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)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.
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 cROOM.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".
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()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.
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)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.
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 cCAB.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".
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()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.
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)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.
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 cQUIZ.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".
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()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.
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)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.
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 cMEDAL.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".
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()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.
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)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.
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 cNURSERY.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".
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()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.
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)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:
Sanjeevani University, Amritsar. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| ADMIN | 25 |
| ACADEMIC | 600 |
| HOSTEL | 120 |
| SPORTS | 50 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| ADMIN | ACADEMIC | 60 m |
| ADMIN | HOSTEL | 160 m |
| ADMIN | SPORTS | 80 m |
| ACADEMIC | HOSTEL | 40 m |
| ACADEMIC | SPORTS | 120 m |
| HOSTEL | SPORTS | 150 m |
Suggest:
Cable layout (star). R marks a repeater.
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:
Senior Secondary School, Jaipur. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| SENIOR | 120 |
| JUNIOR | 40 |
| ADMIN | 25 |
| HOSTEL | 60 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| SENIOR | JUNIOR | 45 m |
| SENIOR | ADMIN | 70 m |
| SENIOR | HOSTEL | 130 m |
| JUNIOR | ADMIN | 60 m |
| JUNIOR | HOSTEL | 150 m |
| ADMIN | HOSTEL | 90 m |
Suggest:
Cable layout (star). R marks a repeater.
City Hospital, Lucknow. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| OPD | 60 |
| LAB | 30 |
| WARDS | 150 |
| PHARMACY | 20 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| OPD | LAB | 70 m |
| OPD | WARDS | 55 m |
| OPD | PHARMACY | 90 m |
| LAB | WARDS | 110 m |
| LAB | PHARMACY | 125 m |
| WARDS | PHARMACY | 40 m |
Suggest:
Cable layout (star). R marks a repeater.
Software company, Pune. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| DEVELOPMENT | 200 |
| TESTING | 80 |
| HR | 25 |
| FINANCE | 35 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| DEVELOPMENT | TESTING | 30 m |
| DEVELOPMENT | HR | 95 m |
| DEVELOPMENT | FINANCE | 140 m |
| TESTING | HR | 60 m |
| TESTING | FINANCE | 105 m |
| HR | FINANCE | 50 m |
Suggest:
Cable layout (star). R marks a repeater.
State University, Bhopal. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| LIBRARY | 50 |
| SCIENCE | 180 |
| ARTS | 70 |
| OFFICE | 40 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| LIBRARY | SCIENCE | 65 m |
| LIBRARY | ARTS | 75 m |
| LIBRARY | OFFICE | 135 m |
| SCIENCE | ARTS | 115 m |
| SCIENCE | OFFICE | 85 m |
| ARTS | OFFICE | 160 m |
Suggest:
Cable layout (star). R marks a repeater.
Bank training centre, Kolkata. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| TRAINING | 90 |
| EXAM | 140 |
| GUEST HOUSE | 30 |
| RECORDS | 45 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| TRAINING | EXAM | 50 m |
| TRAINING | GUEST HOUSE | 95 m |
| TRAINING | RECORDS | 110 m |
| EXAM | GUEST HOUSE | 125 m |
| EXAM | RECORDS | 80 m |
| GUEST HOUSE | RECORDS | 60 m |
Suggest:
Cable layout (star). R marks a repeater.
Publishing house, Chandigarh. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| EDITORIAL | 75 |
| DESIGN | 110 |
| PRINTING | 35 |
| STORE | 15 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| EDITORIAL | DESIGN | 40 m |
| EDITORIAL | PRINTING | 70 m |
| EDITORIAL | STORE | 100 m |
| DESIGN | PRINTING | 90 m |
| DESIGN | STORE | 145 m |
| PRINTING | STORE | 55 m |
Suggest:
Cable layout (star). R marks a repeater.
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
Number of computers
| Block | Computers |
|---|---|
| COACHING | 55 |
| HOSTEL | 95 |
| MEDICAL | 20 |
| OFFICE | 30 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| COACHING | HOSTEL | 60 m |
| COACHING | MEDICAL | 85 m |
| COACHING | OFFICE | 120 m |
| HOSTEL | MEDICAL | 105 m |
| HOSTEL | OFFICE | 75 m |
| MEDICAL | OFFICE | 45 m |
Suggest:
Cable layout (star). R marks a repeater.
Vidya Public School, Nagpur. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| ADMIN | 45 |
| LIBRARY | 160 |
| SCIENCE | 40 |
| HOSTEL | 15 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| ADMIN | LIBRARY | 130 m |
| ADMIN | SCIENCE | 80 m |
| ADMIN | HOSTEL | 155 m |
| LIBRARY | SCIENCE | 90 m |
| LIBRARY | HOSTEL | 130 m |
| SCIENCE | HOSTEL | 170 m |
Suggest:
Cable layout (star). R marks a repeater.
Sunrise Textiles, Surat. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| HR | 70 |
| SALES | 140 |
| PRODUCTION | 125 |
| STORE | 205 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| HR | SALES | 55 m |
| HR | PRODUCTION | 70 m |
| HR | STORE | 75 m |
| SALES | PRODUCTION | 135 m |
| SALES | STORE | 125 m |
| PRODUCTION | STORE | 40 m |
Suggest:
Cable layout (star). R marks a repeater.
Lifeline Hospital, Patna. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| OPD | 215 |
| LAB | 225 |
| WARD | 120 |
| PHARMACY | 110 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| OPD | LAB | 40 m |
| OPD | WARD | 70 m |
| OPD | PHARMACY | 180 m |
| LAB | WARD | 150 m |
| LAB | PHARMACY | 160 m |
| WARD | PHARMACY | 175 m |
Suggest:
Cable layout (star). R marks a repeater.
TechNova Institute, Hyderabad. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| RECEPTION | 220 |
| TRAINING | 95 |
| DATA CENTRE | 150 |
| CANTEEN | 175 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| RECEPTION | TRAINING | 65 m |
| RECEPTION | DATA CENTRE | 55 m |
| RECEPTION | CANTEEN | 145 m |
| TRAINING | DATA CENTRE | 170 m |
| TRAINING | CANTEEN | 80 m |
| DATA CENTRE | CANTEEN | 160 m |
Suggest:
Cable layout (star). R marks a repeater.
Green Valley Polytechnic, Dehradun. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| MAIN | 30 |
| ANNEXE | 115 |
| WORKSHOP | 165 |
| GUEST HOUSE | 95 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| MAIN | ANNEXE | 110 m |
| MAIN | WORKSHOP | 45 m |
| MAIN | GUEST HOUSE | 70 m |
| ANNEXE | WORKSHOP | 150 m |
| ANNEXE | GUEST HOUSE | 95 m |
| WORKSHOP | GUEST HOUSE | 90 m |
Suggest:
Cable layout (star). R marks a repeater.
Daily Times Press, Bhopal. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| EDITORIAL | 195 |
| PRINTING | 40 |
| MARKETING | 70 |
| DISPATCH | 100 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| EDITORIAL | PRINTING | 120 m |
| EDITORIAL | MARKETING | 40 m |
| EDITORIAL | DISPATCH | 40 m |
| PRINTING | MARKETING | 155 m |
| PRINTING | DISPATCH | 130 m |
| MARKETING | DISPATCH | 125 m |
Suggest:
Cable layout (star). R marks a repeater.
Himalaya Sports School, Gangtok. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| JUNIOR | 110 |
| SENIOR | 200 |
| SPORTS | 215 |
| OFFICE | 175 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| JUNIOR | SENIOR | 135 m |
| JUNIOR | SPORTS | 40 m |
| JUNIOR | OFFICE | 115 m |
| SENIOR | SPORTS | 30 m |
| SENIOR | OFFICE | 120 m |
| SPORTS | OFFICE | 130 m |
Suggest:
Cable layout (star). R marks a repeater.
Orbit Labs, Bengaluru. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| RESEARCH | 120 |
| DESIGN | 215 |
| TESTING | 130 |
| ACCOUNTS | 175 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| RESEARCH | DESIGN | 75 m |
| RESEARCH | TESTING | 110 m |
| RESEARCH | ACCOUNTS | 90 m |
| DESIGN | TESTING | 160 m |
| DESIGN | ACCOUNTS | 105 m |
| TESTING | ACCOUNTS | 100 m |
Suggest:
Cable layout (star). R marks a repeater.
City Degree College, Kanpur. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| ARTS | 80 |
| COMMERCE | 135 |
| SCIENCE | 160 |
| ADMIN | 70 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| ARTS | COMMERCE | 170 m |
| ARTS | SCIENCE | 105 m |
| ARTS | ADMIN | 70 m |
| COMMERCE | SCIENCE | 65 m |
| COMMERCE | ADMIN | 125 m |
| SCIENCE | ADMIN | 30 m |
Suggest:
Cable layout (star). R marks a repeater.
QuickKart Logistics, Noida. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| BILLING | 165 |
| CUSTOMER CARE | 235 |
| WAREHOUSE | 95 |
| IT | 215 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| BILLING | CUSTOMER CARE | 135 m |
| BILLING | WAREHOUSE | 120 m |
| BILLING | IT | 115 m |
| CUSTOMER CARE | WAREHOUSE | 50 m |
| CUSTOMER CARE | IT | 60 m |
| WAREHOUSE | IT | 85 m |
Suggest:
Cable layout (star). R marks a repeater.
Saraswati Vidya Mandir, Ranchi. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| ADMIN | 250 |
| LIBRARY | 225 |
| SCIENCE | 85 |
| HOSTEL | 45 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| ADMIN | LIBRARY | 155 m |
| ADMIN | SCIENCE | 40 m |
| ADMIN | HOSTEL | 75 m |
| LIBRARY | SCIENCE | 105 m |
| LIBRARY | HOSTEL | 95 m |
| SCIENCE | HOSTEL | 50 m |
Suggest:
Cable layout (star). R marks a repeater.
Bharat Auto Parts, Pune. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| HR | 225 |
| SALES | 95 |
| PRODUCTION | 155 |
| STORE | 250 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| HR | SALES | 50 m |
| HR | PRODUCTION | 70 m |
| HR | STORE | 140 m |
| SALES | PRODUCTION | 125 m |
| SALES | STORE | 95 m |
| PRODUCTION | STORE | 70 m |
Suggest:
Cable layout (star). R marks a repeater.
Arogya Medical Centre, Kochi. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| OPD | 125 |
| LAB | 90 |
| WARD | 195 |
| PHARMACY | 180 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| OPD | LAB | 95 m |
| OPD | WARD | 160 m |
| OPD | PHARMACY | 130 m |
| LAB | WARD | 110 m |
| LAB | PHARMACY | 165 m |
| WARD | PHARMACY | 30 m |
Suggest:
Cable layout (star). R marks a repeater.
SkillUp Academy, Indore. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| RECEPTION | 60 |
| TRAINING | 140 |
| DATA CENTRE | 200 |
| CANTEEN | 110 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| RECEPTION | TRAINING | 60 m |
| RECEPTION | DATA CENTRE | 70 m |
| RECEPTION | CANTEEN | 85 m |
| TRAINING | DATA CENTRE | 165 m |
| TRAINING | CANTEEN | 120 m |
| DATA CENTRE | CANTEEN | 60 m |
Suggest:
Cable layout (star). R marks a repeater.
Ganga Engineering Works, Varanasi. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| MAIN | 210 |
| ANNEXE | 135 |
| WORKSHOP | 95 |
| GUEST HOUSE | 230 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| MAIN | ANNEXE | 75 m |
| MAIN | WORKSHOP | 160 m |
| MAIN | GUEST HOUSE | 70 m |
| ANNEXE | WORKSHOP | 60 m |
| ANNEXE | GUEST HOUSE | 160 m |
| WORKSHOP | GUEST HOUSE | 45 m |
Suggest:
Cable layout (star). R marks a repeater.
Navyug Publications, Chandigarh. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| EDITORIAL | 55 |
| PRINTING | 15 |
| MARKETING | 140 |
| DISPATCH | 225 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| EDITORIAL | PRINTING | 120 m |
| EDITORIAL | MARKETING | 60 m |
| EDITORIAL | DISPATCH | 75 m |
| PRINTING | MARKETING | 120 m |
| PRINTING | DISPATCH | 165 m |
| MARKETING | DISPATCH | 70 m |
Suggest:
Cable layout (star). R marks a repeater.
Delhi Model School, Delhi. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| JUNIOR | 185 |
| SENIOR | 140 |
| SPORTS | 50 |
| OFFICE | 220 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| JUNIOR | SENIOR | 40 m |
| JUNIOR | SPORTS | 115 m |
| JUNIOR | OFFICE | 180 m |
| SENIOR | SPORTS | 95 m |
| SENIOR | OFFICE | 70 m |
| SPORTS | OFFICE | 170 m |
Suggest:
Cable layout (star). R marks a repeater.
Pixel Design Studio, Mumbai. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| RESEARCH | 35 |
| DESIGN | 75 |
| TESTING | 135 |
| ACCOUNTS | 180 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| RESEARCH | DESIGN | 120 m |
| RESEARCH | TESTING | 80 m |
| RESEARCH | ACCOUNTS | 130 m |
| DESIGN | TESTING | 60 m |
| DESIGN | ACCOUNTS | 50 m |
| TESTING | ACCOUNTS | 40 m |
Suggest:
Cable layout (star). R marks a repeater.
National Commerce College, Jaipur. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| ARTS | 210 |
| COMMERCE | 65 |
| SCIENCE | 220 |
| ADMIN | 120 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| ARTS | COMMERCE | 165 m |
| ARTS | SCIENCE | 95 m |
| ARTS | ADMIN | 90 m |
| COMMERCE | SCIENCE | 140 m |
| COMMERCE | ADMIN | 165 m |
| SCIENCE | ADMIN | 50 m |
Suggest:
Cable layout (star). R marks a repeater.
FreshCart Retail, Lucknow. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| BILLING | 120 |
| CUSTOMER CARE | 75 |
| WAREHOUSE | 45 |
| IT | 70 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| BILLING | CUSTOMER CARE | 105 m |
| BILLING | WAREHOUSE | 120 m |
| BILLING | IT | 50 m |
| CUSTOMER CARE | WAREHOUSE | 155 m |
| CUSTOMER CARE | IT | 140 m |
| WAREHOUSE | IT | 110 m |
Suggest:
Cable layout (star). R marks a repeater.
Gyan Deep School, Raipur. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| ADMIN | 55 |
| LIBRARY | 170 |
| SCIENCE | 35 |
| HOSTEL | 135 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| ADMIN | LIBRARY | 65 m |
| ADMIN | SCIENCE | 175 m |
| ADMIN | HOSTEL | 160 m |
| LIBRARY | SCIENCE | 110 m |
| LIBRARY | HOSTEL | 130 m |
| SCIENCE | HOSTEL | 115 m |
Suggest:
Cable layout (star). R marks a repeater.
Coastal Foods, Visakhapatnam. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| HR | 80 |
| SALES | 240 |
| PRODUCTION | 195 |
| STORE | 220 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| HR | SALES | 75 m |
| HR | PRODUCTION | 170 m |
| HR | STORE | 110 m |
| SALES | PRODUCTION | 180 m |
| SALES | STORE | 40 m |
| PRODUCTION | STORE | 65 m |
Suggest:
Cable layout (star). R marks a repeater.
Care Plus Hospital, Ahmedabad. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| OPD | 80 |
| LAB | 195 |
| WARD | 230 |
| PHARMACY | 160 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| OPD | LAB | 155 m |
| OPD | WARD | 30 m |
| OPD | PHARMACY | 165 m |
| LAB | WARD | 55 m |
| LAB | PHARMACY | 90 m |
| WARD | PHARMACY | 145 m |
Suggest:
Cable layout (star). R marks a repeater.
Future Minds Institute, Chennai. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| RECEPTION | 135 |
| TRAINING | 220 |
| DATA CENTRE | 65 |
| CANTEEN | 195 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| RECEPTION | TRAINING | 120 m |
| RECEPTION | DATA CENTRE | 60 m |
| RECEPTION | CANTEEN | 70 m |
| TRAINING | DATA CENTRE | 40 m |
| TRAINING | CANTEEN | 70 m |
| DATA CENTRE | CANTEEN | 35 m |
Suggest:
Cable layout (star). R marks a repeater.
Shakti Tools, Ludhiana. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| MAIN | 150 |
| ANNEXE | 60 |
| WORKSHOP | 205 |
| GUEST HOUSE | 100 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| MAIN | ANNEXE | 70 m |
| MAIN | WORKSHOP | 95 m |
| MAIN | GUEST HOUSE | 130 m |
| ANNEXE | WORKSHOP | 105 m |
| ANNEXE | GUEST HOUSE | 75 m |
| WORKSHOP | GUEST HOUSE | 50 m |
Suggest:
Cable layout (star). R marks a repeater.
Lok Samachar, Guwahati. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| EDITORIAL | 65 |
| PRINTING | 60 |
| MARKETING | 225 |
| DISPATCH | 215 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| EDITORIAL | PRINTING | 135 m |
| EDITORIAL | MARKETING | 170 m |
| EDITORIAL | DISPATCH | 30 m |
| PRINTING | MARKETING | 35 m |
| PRINTING | DISPATCH | 35 m |
| MARKETING | DISPATCH | 170 m |
Suggest:
Cable layout (star). R marks a repeater.
Seven Hills School, Shimla. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| JUNIOR | 180 |
| SENIOR | 60 |
| SPORTS | 95 |
| OFFICE | 170 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| JUNIOR | SENIOR | 55 m |
| JUNIOR | SPORTS | 130 m |
| JUNIOR | OFFICE | 105 m |
| SENIOR | SPORTS | 85 m |
| SENIOR | OFFICE | 140 m |
| SPORTS | OFFICE | 125 m |
Suggest:
Cable layout (star). R marks a repeater.
Nimbus Software, Kolkata. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| RESEARCH | 75 |
| DESIGN | 115 |
| TESTING | 220 |
| ACCOUNTS | 250 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| RESEARCH | DESIGN | 55 m |
| RESEARCH | TESTING | 165 m |
| RESEARCH | ACCOUNTS | 75 m |
| DESIGN | TESTING | 150 m |
| DESIGN | ACCOUNTS | 135 m |
| TESTING | ACCOUNTS | 140 m |
Suggest:
Cable layout (star). R marks a repeater.
Triveni College, Prayagraj. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| ARTS | 25 |
| COMMERCE | 120 |
| SCIENCE | 245 |
| ADMIN | 65 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| ARTS | COMMERCE | 95 m |
| ARTS | SCIENCE | 150 m |
| ARTS | ADMIN | 110 m |
| COMMERCE | SCIENCE | 60 m |
| COMMERCE | ADMIN | 180 m |
| SCIENCE | ADMIN | 125 m |
Suggest:
Cable layout (star). R marks a repeater.
MetroMart, Bhubaneswar. It has four blocks, as shown in the layout.
Layout of the blocks
Number of computers
| Block | Computers |
|---|---|
| BILLING | 160 |
| CUSTOMER CARE | 215 |
| WAREHOUSE | 145 |
| IT | 125 |
Distance between blocks
| From | To | Distance |
|---|---|---|
| BILLING | CUSTOMER CARE | 105 m |
| BILLING | WAREHOUSE | 100 m |
| BILLING | IT | 70 m |
| CUSTOMER CARE | WAREHOUSE | 135 m |
| CUSTOMER CARE | IT | 85 m |
| WAREHOUSE | IT | 80 m |
Suggest:
Cable layout (star). R marks a repeater.
Tap an option to check your answer at once; your score is saved
Ten multiple-choice questions picked at random. Tap an option to answer. You get your score at the end.
Twenty ready papers with blueprints and a random paper maker, all on the design of the CBSE Sample Question Paper 2026-27
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.
Downloads and printing work when this page is opened as an HTML file in a browser.
Choose Paper 1 to Paper 20, or make a random paper. The blueprint and the paper open here.
Read this the evening before and again at the exam centre gate
import pickle, import csv or import mysql.connectorcommit() after INSERT, UPDATE, DELETE= NULL in place of IS NULL