Python PYQ Solutions
Python PYQ Solutions
1a. Negative indexes refer to elements from the end of a list/string. -1 is last, -2 is second last, etc.
1b.
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)
1c.
class Parent:
def __init__(self):
print("Parent")
class Child(Parent):
def __init__(self):
super().__init__()
print("Child")
1d.
import sqlite3
conn = sqlite3.connect('mydb.db')
cursor = conn.cursor()
conn.close()
1e. The finally block ensures execution of code regardless of exceptions (e.g., closing files).
2a.
s = "Silicon"
for i in range(0, len(s), 2):
print(s[i], end="")
2c.
def IntersecOfSets(arr1, arr2, arr3):
return list(set(arr1) & set(arr2) & set(arr3))
2e.
import re
text = "Ain is here"
if re.search(r'\bain', text, re.IGNORECASE):
print("Found")
--- SECTION 3 (7 MARKS) ---
3a.
import re
def validate_password(pwd):
if len(pwd) < 8: return "Too short"
if not re.search(r'[A-Z]', pwd): return "No uppercase"
if not re.search(r'[a-z]', pwd): return "No lowercase"
if not re.search(r'[0-9]', pwd): return "No digit"
return "Valid"
3b.
n = int(input())
if n % 2: print("Odd")
elif 2 <= n <= 5: print("Even 2-5")
elif 6 <= n <= 20: print("Even 6-20")
else: print("Large Even")
4a.
def returnSum(myDict):
lst = [myDict[k] for k in myDict if k in myDict]
i, s = 0, 0
while i < len(lst):
s += lst[i]
i += 1
return s
4b.
tup = (1, 2, 3, 4)
s = sum(tup[i] for i in range(len(tup)) if i % 2 == 0)
p=1
for i in range(len(tup)):
if i % 2 != 0:
p *= tup[i]
print(s, p)
5a.
class MinBalanceException(Exception): pass
class Account:
def __init__(self, name, no, bal):
self.name, self.no, self.bal = name, no, bal
def Withdraw(self, amt):
if self.bal - amt < 1000:
raise MinBalanceException()
self.bal -= amt
5b.
try:
expr = input()
print(10/int(expr))
eval("x === x")
except ZeroDivisionError:
print("Zero Division")
except ValueError:
print("Value Error")
except SyntaxError:
print("Syntax Error")
6a.
import sqlite3
conn = sqlite3.connect('Stud_DB.db')
cur = conn.cursor()
cur.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cur.fetchall())
cur.execute("INSERT INTO Stud_TAB VALUES (1, 'Alice', 85)")
conn.commit()
cur.execute("SELECT * FROM Stud_TAB")
print(cur.fetchall())
conn.close()
6b.
f = open("demo.txt", "w+")
f.write("SeekTestData")
f.seek(0)
print(f.read(4))
f.seek(5)
print(f.read())
f.close()
7a.
import re
def check(s):
return "Valid" if re.match("^[A-Za-z0-9]+$", s) else "Invalid"
7b.
class Base:
def __init__(self):
self.a = "Public"
self.__c = "Private"
class Derived(Base):
def __init__(self):
Base.__init__(self)
try: print(self.__c)
except: print("Private inaccessible")
b = Base()
print(b.a)