0% found this document useful (0 votes)
3 views

Python QB2

The document covers various Python programming concepts including lambda functions, data hiding, file handling, and object-oriented features. It provides examples for built-in functions, exception handling, and modules, as well as details on libraries like Matplotlib, Pandas, and NumPy. Additionally, it discusses inheritance, method overloading, and file operations.
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)
3 views

Python QB2

The document covers various Python programming concepts including lambda functions, data hiding, file handling, and object-oriented features. It provides examples for built-in functions, exception handling, and modules, as well as details on libraries like Matplotlib, Pandas, and NumPy. Additionally, it discusses inheritance, method overloading, and file operations.
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
You are on page 1/ 6

Q1.

2 Marks Each

1. Use of lambda function in Python:


Lambda functions are anonymous functions defined using the `lambda` keyword for short,
one-line operations. They are useful in functional programming with `map()`, `filter()`, etc.
Example: `x = lambda a: a + 10` → `print(x(5))` outputs `15`.

2. Data Hiding concept and two advantages:


Data Hiding restricts direct access to class attributes using double underscores (`__`) to make
them private, accessible only via methods.
Advantages:
- Enhances security by preventing unauthorized changes.
- Simplifies maintenance by hiding internal details.

3. Syntax of fopen:
Python uses `open()` instead of `fopen` (a C function). Syntax:
```python
file_object = open("filename", "mode")
```
Example: `f = open("data.txt", "r")` opens file for reading.

4. Four Python built-in functions with examples:


- `len()`: Returns length. Example: `len("Python")` → `6`.
- `print()`: Displays output. Example: `print("Hi")` → `Hi`.
- `input()`: Takes user input. Example: `x = input("Enter: ")`.
- `range()`: Generates numbers. Example: `list(range(3))` → `[0, 1, 2]`.

5. Method Overloading example:


Python doesn’t support traditional method overloading but uses default or variable arguments.
```python
class Calculator:
def sum(self, a, b=0):
return a + b
calc = Calculator()
print(calc.sum(5)) # Output: 5
print(calc.sum(5, 3)) # Output: 8
```

6. Python program for zero division error:


```python
try:
num = int(input("Enter number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero not allowed!")
```

7. Use of matplotlib package:


Matplotlib is a plotting library used to create 2D graphs and visualizations like line plots, bar
charts, etc., for data representation.
Example: Plotting `y = x^2`.

8. Object-oriented features in Python:


- Encapsulation: Bundling data and methods.
- Inheritance: Reusing parent class code.
- Polymorphism: Same method, different behavior.
- Abstraction: Hiding complexity.

9. Modes of opening a file in Python:


- `"r"`: Read (default).
- `"w"`: Write (overwrites).
- `"a"`: Append.
- `"r+"`: Read and write.

10. Module explanation and definition:


A module is a `.py` file with functions, classes, or variables for code reuse.
Define: Create `maths.py` with:
```python
def add(a, b):
return a + b
```
Use: `import maths`.

11. Class Student with methods:


```python
class Student:
def read_data(self):
self.name = input("Enter Name: ")
self.roll = int(input("Enter Roll No: "))
def display_data(self):
print("Name:", self.name)
print("Roll No:", self.roll)
s = Student()
s.read_data()
s.display_data()
```
12. Try-except-else-finally block with example:
- `try`: Tests code.
- `except`: Catches errors.
- `else`: Runs if no error.
- `finally`: Always runs.
```python
try:
x = 10 / 5
except ZeroDivisionError:
print("Error!")
else:
print("Result:", x)
finally:
print("Finished")
```

13. Purpose of self keyword:


`self` represents the current object in a class, used to access its attributes and methods.

14. Use of super():


`super()` calls a parent class method, often used in inheritance.
Example: `super().__init__()` calls parent’s constructor.

15. Use of __init__ method:


`__init__` initializes object attributes when created.
Example: `def __init__(self): self.x = 10`.

16. Four methods of os module:


- `os.mkdir()`: Creates directory.
- `os.remove()`: Deletes file.
- `os.getcwd()`: Gets current directory.
- `os.listdir()`: Lists directory contents.

17. Two functions to write data in a file:


- `write()`: Writes a string.
- `writelines()`: Writes a list of strings.

---

### Q2. 4 Marks Each

1. Program importing user-defined module:


```python
# mymodule.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b

# main.py
import mymodule
print("Sum:", mymodule.add(5, 3)) # Output: 8
print("Difference:", mymodule.subtract(5, 3)) # Output: 2
```

2. Pandas package with example:


Pandas is used for data analysis with structures like DataFrames.
```python
import pandas as pd
data = {"Roll": [1, 2], "Marks": [85, 90]}
df = pd.DataFrame(data)
print(df)
```

3. Program for multiple and multilevel inheritance:


```python
class A:
def showA(self):
print("Class A")
class B:
def showB(self):
print("Class B")
class C(A, B): # Multiple
def showC(self):
print("Class C")
class D(C): # Multilevel
def showD(self):
print("Class D")
obj = D()
obj.showA() # Output: Class A
obj.showC() # Output: Class C
```

4. Program to read from end and write to another file:


```python
f1 = open("first.txt", "r")
content = f1.read()
reversed_content = content[::-1]
f1.close()
f2 = open("second.txt", "w")
f2.write(reversed_content)
f2.close()
print("Content reversed and written!")
```

5. Program using user-defined package:


```python
# mypackage/calc.py
def multiply(a, b):
return a * b

# main.py
from mypackage import calc
result = calc.multiply(4, 5)
print("Result:", result) # Output: 20
```

6. NumPy package with example:


NumPy supports numerical operations with arrays.
```python
import numpy as np
arr = np.array([1, 2, 3])
print("Array:", arr * 2) # Output: [2 4 6]
```

7. Parent Animal and child Herbivorous class:


```python
class Animal:
def feed(self):
print("Animal eats food")
class Herbivorous(Animal):
def feed(self):
print("Herbivorous eats plants")
obj = Herbivorous()
obj.feed() # Output: Herbivorous eats plants
```

8. Count vowels, consonants, characters, spaces in file:


```python
f = open("sample.txt", "r")
text = f.read()
vowels = "aeiouAEIOU"
v, c, s, t = 0, 0, 0, 0
for ch in text:
t += 1
if ch in vowels:
v += 1
elif ch.isalpha():
c += 1
elif ch == " ":
s += 1
print("Vowels:", v)
print("Consonants:", c)
print("Spaces:", s)
print("Total:", t)
f.close()
```

9. Exception Handling in Python:


Exception handling uses `try`, `except`, `else`, and `finally` to manage errors and prevent
crashes.
Example: See Q1.12.

10. Program to read 10 characters from a file:


```python
f = open("data.txt", "r")
chars = f.read(10)
print("First 10 characters:", chars)
f.close()
```

11. Modes for file opening in Python:


- `"r"`: Read only.
- `"w"`: Write (overwrites).
- `"a"`: Append to end.
- `"r+"`: Read and write.
- `"b"`: Binary mode (e.g., `"rb"`).

You might also like