PYTHON CLASS TEST SOLUTIONS
Q1. Attempt any FIVE:
a) Features, Keywords, Modes:
- Features: Easy to learn, open-source, interpreted, object-oriented, large standard library
- Keywords: if, else, elif, while, for, def, class, try, except
- Modes: r, w, a, r+, w+, a+
b) List vs Tuple:
- List is mutable, Tuple is immutable
- [] vs ()
- Lists consume more memory
- Example: lst = [1,2], tup = (1,2)
c) Class & Object:
class Student:
pass
s = Student()
d) read() vs readline():
- read(): whole file
- readline(): one line
e) Abstraction vs Hiding:
- Abstraction: shows essential, hides implementation
- Hiding: restrict access using private members
f) Comments:
- # single line
- ''' ''' or multi-line
g) Local vs Global:
- Local: inside function
- Global: outside function
h) File operations: open, read, write
- Modes: r, w, a, r+, w+
i) Data structures: List, Tuple, Set, Dict
Q2. Attempt any THREE:
a) Operators:
- Membership: in, not in
- Bitwise: &, |, ^, ~
- Assignment: =, +=
- Identity: is, is not
b) Dictionary:
d = {1: "One"}
d[2] = "Two"
[Link](1)
print([Link]())
c) Built-in Functions:
- len(), type(), str(), int()
d) List & Tuple methods:
- List: append(), remove()
- Tuple: count(), index()
e) Programs:
- Factorial:
def fact(n): return 1 if n==0 else n*fact(n-1)
- If-else ladder:
if a>0: ...
elif a==0: ...
else: ...
- Pattern:
for i in range(7,0,-2): print("10"*(i//2)+"1")
f) Student class:
class Student:
def __init__(self):
...
def read(self): ...
def display(self): ...
Q3. Attempt any THREE:
a) Set ops:
s = {1,2,3}; [Link](4); [Link](2)
b) Module:
# [Link]
def greet(name): print("Hello", name)
# [Link]
import mymodule
[Link]("Alice")
c) Indexing:
s = "Python"; s[0], s[-1]
d) File copy:
with open("[Link]") as f1, open("[Link]","w") as f2: [Link]([Link]())
e) Set ops:
A|B, A&B, A-B
Q4. Attempt any THREE:
a) List vs Dict:
List uses index, Dict uses keys
b) File modes: 'r', 'w', 'a'
c) Overloading/Overriding:
Python supports overriding
d) Import module:
import calc; [Link]()
e) PASS, ELSE, IF-ELSE
Q5. Attempt any TWO:
a) Palindrome:
n = 121; str(n)[::-1] == str(n)
b) Write & append:
f = open("[Link]","w"); [Link]("Hi"); [Link]()
c) Multiple inheritance:
class A: ..., class B: ..., class C(A,B): ...
d) Inheritance:
class Emp: ..., class Manager(Emp): ...
e) Employee class:
class Employee:
def __init__(self, id, name): ...
def display(self): ...
f) fruit = 'banana'
fruit[:3] = 'ban', fruit[3:] = 'ana'
Q6. Attempt any TWO:
a) Try-except:
try: ... except ZeroDivisionError: ...
b) Student class with read/display
c) File modes: r, w, a with examples
d) Min/Max of list:
max(lst), min(lst)
e) Sum of digits:
while n>0: total += n%10; n//=10