0% found this document useful (0 votes)
9 views5 pages

Python Class Test Solutions Overview

Uploaded by

om250282
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

Python Class Test Solutions Overview

Uploaded by

om250282
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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

Common questions

Powered by AI

File modes in Python determine how a file is opened and interacted with. The 'r' mode opens a file for reading and is the default mode. 'w' opens a file for writing, erasing the previous content if the file exists. 'a' mode opens a file for appending, adding content to the end. 'r+' allows for both reading and writing without truncating the file, whereas 'w+' is used for reading and writing, but it truncates the file to zero length. Lastly, 'a+' opens a file for both reading and appending, positioning the cursor at the end of the file .

The 'def' keyword in Python is used to define a function. It is followed by the function name and a set of parentheses, which may include parameters. Function definitions with 'def' encapsulate reusable code blocks that execute when the function is called. 'def' is a fundamental keyword in Python that introduces functions, promoting modularity and code reusability .

Abstraction in object-oriented programming involves highlighting the essential features of a system while concealing the complex details, enabling a focus on high-level functionalities. Information hiding, on the other hand, specifically restricts access to parts of an object using private members, ensuring that certain components are not exposed to the rest of the program. While abstraction provides a conceptual model, information hiding enforces access restrictions on data .

In Python, 'try' and 'except' blocks are used for handling exceptions. A typical example involves handling a ZeroDivisionError, which occurs when a division by zero is attempted. Here is an example: try executing 'result = 10 / 0', and include an 'except ZeroDivisionError:' block to handle the error by printing a message like 'Division by zero is not allowed'. These blocks prevent the program from crashing due to unexpected errors .

Python supports multiple inheritance by allowing a class to inherit attributes and methods from more than one parent class. This is executed by defining a class with multiple base classes in its declaration, such as class C(A, B), where 'C' inherits from both 'A' and 'B'. The implications for class design include increased flexibility and reusability of code, but they also introduce complexity, such as the diamond problem, which requires the use of method resolution order (MRO) to effectively manage inheritance chains .

The 'read()' method in Python file handling reads the entire contents of a file and returns it as a single string, which is useful for reading all the data at once. In contrast, 'readline()' reads a single line from the file, which is useful for processing files line by line. Therefore, 'read()' is more appropriate when processing smaller files entirely, whereas 'readline()' is more efficient for large files that require line-by-line processing .

Lists in Python are mutable, meaning their elements can be changed, while tuples are immutable and cannot be altered once created. Lists consume more memory compared to tuples due to their dynamic nature. Lists are enclosed in square brackets '[]', whereas tuples are enclosed in parentheses '()'. Additionally, lists provide more flexibility at the cost of efficiency, while tuples provide performance advantages due to their immutability .

Python's list method 'append()' allows elements to be added at the end of a list, demonstrating the mutable nature of lists, facilitating dynamic data management. In contrast, the 'count()' function for tuples returns the number of times a specified value appears in a tuple, supporting efficient data retrieval despite tuples being immutable. Together, these methods showcase different approaches to data manipulation in Python's versatile data structures .

Indexing operations in Python provide a mechanism for accessing specific characters within a string by their positional indices, supporting both positive indexing from the start and negative indexing from the end. This flexibility enhances data manipulation capabilities, allowing for efficient string operations such as reversal, slicing, and selective data retrieval, which are crucial in text processing and analysis applications .

Python supports method overriding by allowing a child class to provide a specific implementation of a method that is already defined in its parent class. This feature is critical in achieving polymorphism. A practical application is in designing modular applications where specific behaviors are necessary for subclasses, such as creating a 'Manager' class that overrides the 'display' method from a generic 'Employee' class to include additional management details .

You might also like