Py Assignment2
Py Assignment2
greet("Alice")
```
result = power(2, 3)
print(result) # Output: 8
```
n_terms = 10
for i in range(n_terms):
print(fibonacci(i))
```
def b(self):
return "Woof!"
d = Dog("Buddy")
print(d.b()) # Output: Woof!
```
a = BankAccount()
a.d(1000)
a.w(500)
print(a.b) # Output: 500
```
class Dog(Animal):
def s(self):
return "Woof!"
class Cat(Animal):
def s(self):
return "Meow!"
d = Dog()
print(d.s()) # Output: Woof!
c = Cat()
print(c.s()) # Output: Meow!
```
class Child(Parent):
def child_method(self):
print("Child method")
c = Child()
c.parent_method() # Output: Parent method
```
- **Multiple Inheritance:**
```python
class Parent1:
def parent1_method(self):
print("Parent 1 method")
class Parent2:
def parent2_method(self):
print("Parent 2 method")
c = Child()
c.parent1_method() # Output: Parent 1 method
c.parent2_method() # Output: Parent 2 method
```
- **Multilevel Inheritance:**
```python
class Grandparent:
def grandparent_method(self):
print("Grandparent method")
class Parent(Grandparent):
def parent_method(self):
print("Parent method")
class Child(Parent):
def child_method(self):
print("Child method")
c = Child()
c.grandparent_method() # Output: Grandparent method
```
class Dog(Animal):
def sound(self):
return "Woof!"
class Cat(Animal):
def sound(self):
return "Meow!"
def make_sound(animal):
return animal.sound()
dog = Dog()
cat = Cat()
print(make_sound(dog)) # Output: Woof!
print(make_sound(cat)) # Output: Meow!
```
- **Method Overriding:**
```python
class Animal:
def sound(self):
return "Generic sound"
class Dog(Animal):
def sound(self):
return "Woof!"
d = Dog()
print(d.sound()) # Output: Woof!
```
- **Operator Overloading:**
```python
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p1 = Point(1, 2)
p2 = Point(3, 4)
p3 = p1 + p2
print(p3.x, p3.y) # Output: 4 6
```
13. **What is Exception Handling? List out and explain Built-in Exceptions:**
- Exception handling is a mechanism to handle errors gracefully during program
execution
.
- Built-in exceptions include `ZeroDivisionError`, `NameError`, `TypeError`,
`ValueError`, `FileNotFoundError`, etc.
14. **How to handle exceptions, explain syntax and give one example:**
- Syntax:
```python
try:
# Code block that may raise an exception
except ExceptionType:
# Code to handle the exception
```
- Example:
```python
try:
x=1/0
except ZeroDivisionError:
print("Cannot divide by zero")
```
20. **Explain The match(), search(), findall() method Function with syntax and an
example:**
- `match(pattern, string)`: Matches a pattern only at the beginning of the string.
- `search(pattern, string)`: Searches for the first occurrence of a pattern in the
string.
- `findall(pattern, string)`: Finds all occurrences of a pattern in the string.
- Example:
```python
import re
text = "The cat sat on the mat."
result = re.match(r'The', text)
```
23. **W.A.P to Retrieve all lines that contain "the" with lower or upper case letter:**
```python
with open("file.txt", "r") as file:
for line in file:
if "the" in line.lower():
print(line)
```
24. **W. A. P to retrieve lines that starts with a and ends with n:**
```python
with open("file.txt", "r") as file:
for line in file:
if line.strip().startswith("a") and line.strip().endswith("n"):
print(line)
```
27. **How to open and close files? Also, give the Syntax for the same:**
- To open a file: `file_object = open(filename, mode)`
- To close a file: `file_object.close()`
- Example:
```python
file = open("example.txt", "r")
# Perform operations on file
file.close()
```
file does not exist, it creates a new file. The file pointer is positioned at the end of
the file, so new data will be written to the end.
34. **Write a program to display all the lines in a file "python.txt" which have the word
"to" in it:**
```python
with open("python.txt", "r") as file:
for line in file:
if "to" in line:
print(line)
```
35. **A text file "PYTHON.TXT" contains alphanumeric text. Write a program that
reads this text file and writes to another file "PYTHON1.TXT" entire file except the
numbers or digits in the file:**
```python
with open("PYTHON.TXT", "r") as file:
with open("PYTHON1.TXT", "w") as new_file:
for line in file:
new_line = ''.join([i for i in line if not i.isdigit()])
new_file.write(new_line)
```
37. **Explain the role of the Regular Expressions in the following snippets:**
i) `p = re.compile('\d+')`: Finds all occurrences of one or more digits in the string.
ii) `p = re.compile('ca+t')`: Finds all occurrences of 'cat', 'caat', 'caaat', etc. in the
string.
iii) `p = re.compile('ca*t')`: Finds all occurrences of 'ct', 'cat', 'caat', 'caaat', etc. in
the string.
iv) `p = re.compile('a/{1,3}b')`: Finds all occurrences of 'a/b', 'a//b', 'a///b', etc. in the
string.
v) `result = re.findall(r'\w*', 'AV is largest Analytics community of India')`: Finds all
words in the string.