0% found this document useful (0 votes)
5 views12 pages

Py Assignment2

A module is a file containing Python code that can define functions, classes, and variables, allowing for code organization and reuse. Advantages of using modules include improved code maintainability, easier debugging, and the ability to share code across different projects. Modules promote the separation of concerns, making it easier to manage large codebases.

Uploaded by

Ritesh bhusara
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)
5 views12 pages

Py Assignment2

A module is a file containing Python code that can define functions, classes, and variables, allowing for code organization and reuse. Advantages of using modules include improved code maintainability, easier debugging, and the ability to share code across different projects. Modules promote the separation of concerns, making it easier to manage large codebases.

Uploaded by

Ritesh bhusara
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/ 12

1.

**Explain the function with example:**


- A function is a block of reusable code that performs a specific task.
- Example:
```python
def greet(name):
print("Hello, " + name + "!")

greet("Alice")
```

2. **Explain the function type with examples:**


- Function types include built-in functions, user-defined functions, and anonymous
functions (lambda functions).
- Examples:
- Built-in function: `print()`, `len()`
- User-defined function: `greet()` from the previous example
- Anonymous function (Lambda function): `lambda x: x * 2`

3. **Explain function Function Arguments with examples:**


- Function arguments are values passed to a function when it's called.
- Example:
```python
def power(x, y):
return x ** y

result = power(2, 3)
print(result) # Output: 8
```

4. **Explain Anonymous Functions (Lambda Functions) with example:**


- Anonymous functions, or lambda functions, are small, unnamed functions.
- Example:
```python
double = lambda x: x * 2
print(double(5)) # Output: 10
```

5. **Explain Recursive Function with an example:**


- A recursive function calls itself until it reaches a base case.
- Example:
```python
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

print(factorial(5)) # Output: 120


```

6. **Write a Python function to check whether a number is even or odd:**


```python
def check_even_odd(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"

print(check_even_odd(5)) # Output: Odd


```

7. **Write a Python program to display Fibonacci series using recursion:**


```python
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

n_terms = 10
for i in range(n_terms):
print(fibonacci(i))
```

8. **What is class, what is object, what is method explain with an example:**


- **Class:** Blueprint for creating objects.
- **Object:** Instance of a class.
- **Method:** Function defined within a class.
- Example:
```python
class Dog:
def __init__(self, name):
self.n = name

def b(self):
return "Woof!"
d = Dog("Buddy")
print(d.b()) # Output: Woof!
```

9. **What is data encapsulation explain with an example:**


- Data encapsulation bundles data and methods within a class.
- Example:
```python
class BankAccount:
def __init__(self):
self.b = 0

def d(self, a):


self.b += a

def w(self, a):


if self.b >= a:
self.b -= a
return a
else:
return "Insufficient funds"

a = BankAccount()
a.d(1000)
a.w(500)
print(a.b) # Output: 500
```

10. **What is inheritance explain with an example:**


- Inheritance allows a class to inherit properties and behaviors from another class.
- Example:
```python
class Animal:
def s(self):
pass # Abstract method

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!
```

11. **Explain different types of inheritance with examples:**


- **Single Inheritance:**
```python
class Parent:
def parent_method(self):
print("Parent method")

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")

class Child(Parent1, Parent2):


def child_method(self):
print("Child 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
```

12. **Explain polymorphism with an example. Explain method overriding and


operator overloading with an example:**
- **Polymorphism:**
```python
class Animal:
def sound(self):
pass

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

def __add__(self, other):


return Point(self.x + other.x, self.y + other.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")
```

15. **Explain except clause with no exception with an example:**


- The `except` clause with no exception specified catches any exception that
occurs.
- Example:
```python
try:
x=1/0
except:
print("An error occurred")
```

16. **Explain except clause with multiple exceptions with an example:**


- The `except` clause can handle multiple exceptions by specifying them in a
tuple.
- Example:
```python
try:
x = int(input("Enter a number: "))
result = 10 / x
except (ValueError, ZeroDivisionError):
print("Invalid input or cannot divide by zero")
```

17. **Explain try and finally block with an example:**


- The `finally` block is executed regardless of whether an exception occurs or not.
- Example:
```python
try:
f = open("example.txt", "r")
# Perform file operations
finally:
f.close()
```

18. **Explain Raising an exception with an example:**


- You can raise an exception using the `raise` statement.
- Example:
```python
x = -1
if x < 0:
raise ValueError("Number must be non-negative")
```
19. **List and explain any five exceptions in Python:**
- `ZeroDivisionError`: Raised when division or modulo by zero occurs.
- `NameError`: Raised when a local or global name is not found.
- `TypeError`: Raised when an operation or function is applied to an object of
inappropriate type.
- `ValueError`: Raised when a built-in operation or function receives an argument
that has the right type but an inappropriate value.
- `FileNotFoundError`: Raised when a file or directory is requested but cannot be
found.

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)
```

21. **Explain Search and Replace with example in the re module:**


- `re.sub(pattern, replacement, string)`: Searches for all occurrences of a pattern
in the string and replaces them with the specified replacement.
- Example:
```python
import re
text = "The cat sat on the mat."
new_text = re.sub(r'cat', 'dog', text)
```

22. **Write all Regular Expression Patterns:**


- Regular expression patterns include `^` (start of string), `$` (end of string), `.`
(any character except newline), `*` (zero or more occurrences), `+` (one or more
occurrences), `?` (zero or one occurrence), `[ ]` (character class), `{ }` (specifies
exact number of occurrences), etc.

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)
```

25. **Differentiate between Text file and Binary files?:**


- Text files contain human-readable characters, while binary files contain encoded
data that may not be human-readable.
- Text files can be opened and edited with a text editor, while binary files require
specific software to interpret their contents.

26. **What are the different operations we can perform on file?**


- Reading from a file
- Writing to a file
- Appending to a file
- Closing a file
- Renaming a file
- Deleting a file

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()
```

28. **What are the different modes to open a file?**


- `r`: Read mode
- `w`: Write mode
- `a`: Append mode
- `r+`: Read and write mode
- `w+`: Write and read mode
- `a+`: Append and read mode
- `rb`, `wb`, `ab`, `rb+`, `wb+`, `ab+` for binary files
29. **Differentiate between file modes r+ and w+ with respect to Python:**
- `r+`: Opens the file for both reading and writing. File pointer starts at the
beginning of the file. Raises `FileNotFoundError` if the file does not exist.
- `w+`: Opens the file for both reading and writing. Truncates the file to zero length
if it exists, or creates a new file if it does not exist.

30. **Write a statement in Python to perform the following operations:**


- To open a text file "MYPET.TXT" in write mode: `file = open("MYPET.TXT", "w")`
- To open a text file "MYPET.TXT" in read mode: `file = open("MYPET.TXT", "r")`
- To open a binary file "LOG.DAT" in read mode: `file = open("LOG.DAT", "rb")`
- To open a binary file "LOG.DAT" in write mode: `file = open("LOG.DAT", "wb")`

31. **Differentiate between 'w' and 'a' modes:**


- `'w'` mode: Opens the file for writing. If the file already exists, it will be truncated
to zero length. If the file does not exist, it creates a new file.
- `'a'` mode: Opens the file for appending. If the

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.

32. **Differentiate between read() and readlines():**


- `read()`: Reads the entire file content as a single string.
- `readlines()`: Reads all lines of the file and returns them as a list of strings, each
representing one line.

33. **Differentiate between Absolute Pathnames and Relative Pathnames:**


- Absolute Pathnames: Specifies the exact location of a file or directory from the
root directory.
- Relative Pathnames: Specifies the location of a file or directory relative to the
current working directory.

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)
```

36. **Explain any 3 methods associated with files in Python:**


- `read()`: Reads the entire file content as a single string.
- `write()`: Writes a string to the file.
- `close()`: Closes the file.

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.

38. **Explain split() method of regular expression with suitable examples:**


- The `split()` method splits a string into a list using a specified pattern as the
delimiter.
- Example:
```python
import re
text = "The quick brown fox"
words = re.split(r'\s', text)
print(words) # Output: ['The', 'quick', 'brown', 'fox']
```

39. **What is module? What are the advantages of using module?**


- A module is a file containing Python code that defines functions, classes, and
variables.
- Advantages of using modules:
- Encapsulation: Organizes code into logical units.
- Reusability: Modules can be imported and reused in different programs.
- Maintainability: Changes made in a module affect all programs importing it.
- Namespace management: Modules provide separate namespaces to avoid
naming conflicts.
40. **Explain various functions of the math module:**
- The `math` module in Python provides various functions for mathematical
operations like trigonometry, logarithms, exponentiation, etc.
- Some functions include `math.sqrt(x)` (square root of x), `math.sin(x)` (sine of x),
`math.log(x)` (natural logarithm of x), `math.exp(x)` (exponential function of x), etc.

You might also like